
$(document).ready(function() {

    ShowPages();

    jQuery('.cycle').cycle({
        speed: 600,
        pause: 1,
        timeout: 6000
    });

    //location_header
    InitLocations();

    //event dlg
    if (location.href.indexOf('events') != -1) {
        $('.tbpageslist a').click(function() {
			if (this.hostname == "www.alliedtelesis.com")
            	ajax_link(this);
			else
				return true;
            return false;
        });
    }


    Initfmsearchproduct();

   
    //hide datasheet
    $('div a[href^=/media/datasheets/]').each(function() {
        if ($(this).text().indexOf('Download ') != -1) {
            //$(this).parent().addClass('removeit');
			$(this).addClass('medium products button ierounded');
				$(this).css('width','auto');
        }
    });
   // $('.removeit').remove();

    //autofields
    InitFormFields();
    InitValidations();
    
	$('#search').keyup(function(e) {
		//alert(e.keyCode);
		if(e.keyCode == 13) {
			//alert('Enter key was pressed.');
			location.href='/search.aspx?keyword='+$('#search').val();
		}
	});

});


 
function FormatSlug(url)
    {
        url = '_' + url + '_';
        url = url.replace("_type_0_", "_").replace("_pid_0_", "_");
        url = url.replace("_type_0.", ".").replace("_pid_0.", ".");
        url = url.substr(1);
        url = url.substr(0, url.length - 1);
       
        return url;
    }


function Initfmsearchproduct() {
    if ($('.fmsearchproduct').length == 0) return;

    $('.fmsearchproduct').submit(function() {
        var params = {};
        $('.fmsearchproduct :input').each(function() {
        if(this.name.length>0)
            params[this.name] = $(this).val();

        });
        $('.finder_results').html('Loading ...');
        $.post('/searchproduct.aspx', params, function(data) {
            $('.finder_results').html(data);
        });
        return false;
    });
    
}


function ajax_link(obj) {
    if ($('.jqmWindow').length == 0) {
        $('body').append('<div class="jqmWindow"><a href="#" class="jqmClose">Close</a><hr /><div class="jqmContent"></div></div>');
    }

    $('.jqmWindow').jqm().jqmShow();
    $('.jqmContent').html('Loading ...');

    $.get('/magicactions.aspx?action=loadlink&url=' + $(obj).attr('href'), function(data) {
        $('.jqmContent').html(data);
    });

}

function Sleep(obj, iMinSecond) {
    if (window.eventList == null)
        window.eventList = new Array();
    var ind = -1;
    for (var i = 0; i < window.eventList.length; i++) {
        if (window.eventList[i] == null) {
            window.eventList[i] = obj;
            ind = i;
            break;
        }
    }
    if (ind == -1) {
        ind = window.eventList.length;
        window.eventList[ind] = obj;
    }
    setTimeout("GoOn(" + ind + ")", iMinSecond);
}
function GoOn(ind) {
    var obj = window.eventList[ind];
    window.eventList[ind] = null;
    if (obj.NextStep) obj.NextStep();
    else obj();
}  

function GetPageSize() {

  var scrW, scrH;

  if(window.innerHeight && window.scrollMaxY) {

    // Mozilla

    scrW = window.innerWidth + window.scrollMaxX;

    scrH = window.innerHeight + window.scrollMaxY;

  } else if(document.body.scrollHeight > document.body.offsetHeight){

    // all but IE Mac

    scrW = document.body.scrollWidth;

    scrH = document.body.scrollHeight;

  } else if(document.body) { // IE Mac

    scrW = document.body.offsetWidth;

    scrH = document.body.offsetHeight;

  }

  

  var winW, winH;

  if(window.innerHeight) { // all except IE

    winW = window.innerWidth;

    winH = window.innerHeight;

  } else if (document.documentElement 

    && document.documentElement.clientHeight) {

    // IE 6 Strict Mode

    winW = document.documentElement.clientWidth; 

    winH = document.documentElement.clientHeight;

  } else if (document.body) { // other

    winW = document.body.clientWidth;

    winH = document.body.clientHeight;

  }

  

  // for small pages with total size less then the viewport

  var pageW = (scrW<winW) ? winW : scrW;

  var pageH = (scrH<winH) ? winH : scrH;

  

  return {PageW:pageW, PageH:pageH, WinW:winW, WinH:winH};

}

function GetPageScroll() {

  var x, y;

  if(window.pageYOffset) {

    // all except IE

    y = window.pageYOffset;

    x = window.pageXOffset;

  } else if(document.documentElement 

    && document.documentElement.scrollTop) {

    // IE 6 Strict

    y = document.documentElement.scrollTop;

    x = document.documentElement.scrollLeft;

  } else if(document.body) {

    // all other IE

    y = document.body.scrollTop;

    x = document.body.scrollLeft; 

  }

  return {X:x, Y:y};

}

var flag =2;

function getLocations(){
	var t = $('.drplocation_type').val();
	var z = $('.drplocation_zip').val();
	
	if (t=="undefined" || t==undefined)
		t = "";
	if (z=="undefined" || z==undefined)
		z = "";
	
	var c = $('.drplocation_country').val();
	var s =$(".locsign").val();
	
	if (s=="undefined" || s==undefined)
		s = "";
	
	var sid = 1;
	if (jQuery(".locid:last").val() == undefined)
		sid = 1;
	else
		sid = Number("0"+jQuery(".locid:last").val());
		
	var dt = "action=getreseller&limit=20&sid="+sid+"&country="+c+"&type="+t+"&zip="+z + "&sign=" + s;	

	$.ajax({
		   url:"/ajax.aspx",
		   data:dt,
		   type:"post",
		   dataType:"text",
		   success:function(res){
							jQuery(".ullocations").append(res);
							flag=1;
							if (res != ""){
								//setTimeout(getLocations, 6000);
								
								$(".loadingmind").show();
								$(window).scroll(function(){
														  	//$(".loadingmind").text((GetPageSize().PageH - GetPageScroll().Y));
														  	if ((GetPageSize().PageH - GetPageScroll().Y)<1500){
																$(window).scroll(function(){});
																if (flag==1){
																	flag = 2;
																	getLocations();	
																}
																
															}
														  });
							}
							else
								$(".loadingmind").hide();
							}
							
		   });
}

function getTypesByCountry(){
	var c = $('.drplocation_country').val();
	
	$.ajax({
	   url:"/ajax.aspx",
	   data:"action=getresellertypes&country="+c,
	   type:"post",
	   dataType:"text",
	   success:function(res){
		   				var temp = "";
						var ares = res.split(',');
		   				for (var t in ares)
						{
							if(ares[t].length>0){
							temp = temp + "<option>" + ares[t] +"</option>";
							}
						}
		   
						var html = ' <select class="drplocation_type" onchange="drplocation_type_zip_change()">'+('<option value="">--  All Types --</option>')+'' + temp + '</select>';
						$('.location_type_fm').html(html);
	   }
	   
	   });
}

function getZipsByCountry(){
	var c = $('.drplocation_country').val();
	
	$.ajax({
	   url:"/ajax.aspx",
	   data:"action=getresellerzips&country="+c,
	   type:"post",
	   dataType:"text",
	   success:function(res){
		   				var temp = "";
						var ares = res.split(',');
		   				for (var t in ares)
						{
							if(ares[t].length>0){
							temp = temp + "<option>" + ares[t] +"</option>";
							}
						}
						var html = ' <select class="drplocation_zip" onchange="drplocation_type_zip_change()">'+('<option value="">--  All Zips --</option>')+'' + temp + '</select>';
						$('.location_zip_fm').html(html);
	   }
	   
	   });
}

function InitLocations() {
    if ($('.location_header').length == 0) return;
    var html = '<option value="">-- Select --</option>';
    $('.location_countries li').each(function() {
		if( $.trim($(this).html()).length>0){
        html += '<option>' + $(this).html() + '</option>';
		}
    });

    $('.location_header').html('Country: <select class="drplocation_country" onchange="drplocation_country_change()">' + html + '</select> <span class="location_type_fm"></span> <span class="location_zip_fm"></span><span class="loadingmind"></span>');
    $('.drplocation_country').val('United States');

    drplocation_country_change_do();
}

function drplocation_country_change_do() {
    $('.location_type_fm').html('Loading ...');
	$('.location_zip_fm').html('Loading ...');
    setTimeout('drplocation_country_change()', 10);
}

function drplocation_country_change() {
    var c = $('.drplocation_country').val();
	
	getTypesByCountry();
	getZipsByCountry();
	
	drplocation_type_zip_change();

}

function drplocation_type_zip_change(){
	var sid = 1;
	if (jQuery(".locid:last").val() == undefined)
		sid = 1;
	else
		sid = Number("0"+jQuery(".locid:last").val());

	$('.ullocations').html("");
	//$(".loadingmind").text("Data still loading..."+sid);
	$(".loadingmind").show();
	getLocations();
	
}


function InitValidations() {
    $('.validate').validate();
}


function ShowPages() {
    var html = '';
    
    var loc = location.href.toLowerCase();
    loc = loc.substr(loc.lastIndexOf('/') + 1);
    loc = loc.substr(0, loc.indexOf('.'));
    if (loc.length == 0) loc = 'default';

    var curi = -1;
    var len = jQuery('.ulpages_fm li').length;
    if (len == 0) {
        return;
    }

    var curli = jQuery('.ulpages_fm a[href*=/' + loc + '.]').parent();




    curi = jQuery('.ulpages_fm li').index(curli);
   // 

    if (jQuery('.ulpages_fm li').length > 0) {
        if (curi == -1) curi = 0;
      
        if (curi > 0) {
            html += '<li><a href="' + $('.ulpages_fm li').eq(curi - 1).find('a').attr('href') + '">Previous</a></li>';
        }
        html += '<li><strong>' + $('.ulpages_fm li').eq(curi).text() + '</strong></li>';
        if (curi < $('.ulpages_fm li').length - 1) {
            html += '<li><a href="' + $('.ulpages_fm li').eq(curi + 1).find('a').attr('href') + '">Next</a></li>';
        }
      
        var u = ( $('.ulpages_fm a:eq(0)').attr('href')+'.aspx').replace('.aspx.aspx','.aspx').replace('.aspx','_showall_true.aspx');
 
        html += '<li><a href="'+u+'">Show All</a></li>';
        $('.ulpages_fm ul').html(html);
        return;
    }

    jQuery(curli).html('<strong>' + jQuery(curli).text() + '</strong>');

    var padding = 3;
    var posb = curi - padding;
    var pose = curi + padding;

    if (posb <= 0) {
        pose = pose - posb + 1;

    }
    if (pose >= len - 1) {
        posb = posb - (pose - len) - 2;
    }

    for (var i = 0; i < len; i++) {
        if ((i >= posb && i <= pose) || i == 0 || i == len - 1) {
            jQuery('.ulpages_fm li').eq(i).addClass('s');
        }
    }
    jQuery('.ulpages_fm li[class!=s]').remove();

    if (len > (2 * padding) + 3) {
        if (curi > padding + 1) {
            jQuery('.ulpages_fm li:first').after('<li class="s">...</li>');
        }
        if (curi < len - padding - 1) {
            jQuery('.ulpages_fm li:last').before('<li class="s">...</li>');
        }
    }
    return;
}


var defaultemail = '';
function drpCountry_change() {
    var c = $('.drpCountry').val();
    if (defaultemail.length == 0) {
        defaultemail = $('.txtemailnotify').val();
    }
    if (defaultemail.length == 0) {
        defaultemail = 'gene_cowan@alliedtelesis.com';
    }
    var t = defaultemail;

    switch (c) {
        case 'Australia':
            {
                t += ',net.cover@alliedtelesis.com.au';
                break;
            }
        case 'Russia':
            {
                t += ',info@alliedtelesyn.ru';
                break;
            }
        default:
            {
                t += ',Netcover_Europe@alliedtelesis.com,richard_lardner@alliedtelesis.com';
                break;
            }
    }

    $('.txtemailnotify').val(t);
}

function InitFormFields() {
    if ($('.autofields').length > 0) {
        if ($('.autofields input[name=_fieldOrder]').length == 0) {
            var fields = ',';
            //alert($('.autofields :input').length);
            $('.autofields :input').each(function(i) {
                var fname = $('.autofields :input').eq(i).attr('name');
                if (fname) {
                    if (fname.substr(0, 1) != '_' && fields.indexOf(',' + fname + ',') == -1 && (',form_redirect,submit,submitbutton,FORM_ID,NEXT_PAGE,').indexOf(',' + fname + ',') == -1) {
                        fields = fields + fname + ',';
                    }
                }
            });
            fields = fields.substr(1);
            if (fields.substr(fields.length - 1) == ',') {
                fields = fields.substr(0, fields.length - 1);
            }

            $('.autofields').append('<input type="hidden" name="_fieldOrder" value="' + fields + '" /> ');

        }
    }
}
