var common = { onInitComplete: function() {}, fadeInTime: 250, menuStates: {} };

jQuery.fn.center = function () {
    //this.css("position","fixed");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
};

function randomString(L){
    var s= '';
    var randomchar=function(){
        var n= Math.floor(Math.random()*35);
        if(n<10) return n; //1-10
        if(n<36) return String.fromCharCode(n+55); //A-Z
        return String.fromCharCode(n+61); //a-z
    }
    while(s.length< L) s+= randomchar();
    return s;
}

common["instanceId"] = randomString(10);
window.name = common.instanceId;

common["onBodyLoaded"] = function() {
    //$("body").fadeTo(1, 0);
    $("body").css("visibility", "hidden");
}

common["startFreeTrial"] = function() {
	$(".trialHost").remove();
	$(".trialIframe").remove();
	trialHost = $("<div>").css({	position: "absolute",
									left: "0px",
									top: $(window).scrollTop() + "px",
									width: "100%",
									height: "100%",
									overflow: "hidden",
									"z-index": 1000}).addClass("trialHost");
	trialIframe = $("<iframe frameborder=\"0\" ALLOWTRANSPARENCY=\"true\">").css({	position: "relative",
										top: "0px",
										left: "0px",
										width: "100%",
										height: "100%",
										background: "transparent",
										overflow: "hidden"}).addClass("trialIframe");
	$(window).scroll(function() { $(".trialHost").css("top", $(window).scrollTop() + "px"); });
	$.fx.off = true;
	if ($.browser.webkit) trialHost.css("visibility", "hidden");
	$(document.body).append(trialHost);
	trialIframe.attr("src", "http://login.icos.co.nz/icoslive/ssu.html?HostID=" + common.instanceId + "&prefix=" + (/^www\./i.test(window.location.host) ? "True" : "False") );
	trialIframe.appendTo(trialHost);
	//if ($.browser.webkit) setTimeout("$(\".trialHost\").css(\"visibility\", \"\");", 1000);
	$(trialIframe).load(function() {
	    trialIframe = $(".trialIframe").get(0);
		if ($.browser.webkit) $(".trialHost").css("visibility", "");
	    try {	    
    	    href = trialIframe.contentWindow.location.href;
    	    if (href == "" || href == null) return;
    	} catch(e) { return; }
    	
        $(".trialHost").remove();
        $(window).unbind("scroll");
        $.fx.off = false;
	});
}

$(document).ready(function() {
	$("<div id=\"dlgLogin\"> \
		<form id=\"frmLogin\" name=\"frmLogin\"> \
			<table> \
				<tr> \
					<td> \
						Username: \
					</td> \
					<td> \
						<input type=\"text\" /> \
					</td> \
				</tr> \
				<tr> \
					<td> \
						Password: \
					</td> \
					<td> \
						<input type=\"password\" id=\"authPassword\" /> \
					</td> \
				</tr> \
			</table> \
		</form> \
	</div>").appendTo(document.body);

	$("#dlgLogin").dialog({
		buttons: {
			Login: function() { 
				$.ajax({
					url: "authentication.ashx",
					data: {Domain: "Agent", User: $("#dlgLogin input:eq(0)").val(), Password: $("#dlgLogin input:eq(1)").val()},
					complete: function(data, status, xhr) {
						if (status != "success") {
							$("#dlgLogin").dialog("widget").effect("shake", { disatance: 10 }, 100);
							return;
						}

						$("#dlgLogin").dialog("close"); 
						$("#content, #altContent, #basicContent").fadeOut(250, function() {window.location = "agent.html" ;});
					}
				});
			}
		},
		modal: true,
		title: "Agent Access",
		resizable: false,
		closeOnEscape: true,
		autoOpen: false
	});

    $("#divMain").center();
    $("#divMain").css("top", "0px");
    $("#divHeader").css("left", $("#divMain").css("left"));
    $("#divHeader").css("width", $("#divMain").width() - 37 + "px");
    $("#copyright").css("width", $("#divMain").width() - 240 + "px");
    
    //$("body").show();
    $("a").click(function(e) {
        //if (e.which != 1) return;
        if ($(this).hasClass("freeTrial") == true) {
            common.startFreeTrial();
            return false;
        }
        if ($(this).attr("target") != "") return;
        if ($(this).attr("href").indexOf("#") == 0) return;
		if (/\.exe/i.test($(this).attr("href")) == true) return;

		if ($(this).hasClass("download") == true) return;

        clickedLink = $(this).attr("href");

		if ($(this).text() == "Agents") {
			$("#dlgLogin").dialog("open");
			return false;
		}

        $("#content, #altContent, #basicContent").fadeOut(250, function() {window.location = clickedLink;});
        return false;
    });

    $(window).resize(function() {
        $("#divMain").center();
        $("#divMain").css("top", "0px");
        $("#divHeader").css("left", $("#divMain").css("left"));
        $("#divHeader").css("width", $("#divMain").width() - 37 + "px");
        $("#copyright").css("width", $("#divMain").width() - 240 + "px");                   
    });
    
    thisYear = (new Date).getYear();
    if (thisYear < 1900) thisYear += 1900;
    
    $("#currentyear").text(thisYear);
    
    $("#divTruckMozaic").fadeTo(0, 0.65, null);
    //$("#divHeader").gradient({from: "002A64", to: "FFFFFF", direction: "vertical"});
    //$("#divHeaderBackground").fadeTo(1, 0.75, null);
    //$(".subnav").fadeTo(1, 0.75, null).hide();    
    //$(".subnav li").fadeTo(1, 0.75, null);
    //$(".subnav :first-child").css("background","none");
    $(".subnav :last-child").css("-moz-border-radius-bottomleft", "3px");
    $(".subnav :last-child").css("-moz-border-radius-bottomright", "3px");
    $(".subnav :last-child").css("-webkit-border-bottom-left-radius", "3px");
    $(".subnav :last-child").css("-webkit-border-bottom-right-radius", "3px");
                                
    //$("ul.sf-menu").superfish();

    $("ul.topnav > li").not(".spacer").each(function() {
        menuText = $(this).children("a:first-child").text().replace(" ", "").toLowerCase();
        common.menuStates[menuText] = "";
    });

    if (typeof window.console != "undefined")
        console.log({ms: common.menuStates});

    $("ul.subnav").css("height", "0px");

    $("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)  

    $("ul.topnav li span").click(function() { //When trigger is clicked...  
   
         //Following events are applied to the subnav itself (moving subnav up and down)  
         //$(this).parent().fadeTo(1, 0.75, null);
         $(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  
   
         $(this).parent().hover(function() {  
         }, function(){  
             $(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
         });  
   
         //Following events are applied to the trigger (Hover events for the trigger)  
         }).hover(function() {  
             $(this).addClass("subhover"); //On hover over, add class "subhover"  
         }, function(){  //On Hover Out  
             $(this).removeClass("subhover"); //On hover out, remove class "subhover"  
     });
     

        $("ul.subnav a").click(function(e) {
            //if (e.which != 1) return;
            $(this).closest("ul.subnav").stop(true).animate({ "height": 0 }, {duration: "fast", queue: false}).fadeOut({duration: "fast", queue: false});
        });

     $("ul.subnav").parent().hover(function() { //When trigger is clicked...  
        /*menuTextNode = $(this).children("a:first-child");
        if (menuTextNode.length == 0) return;
        if (typeof $(menuTextNode[0]).text() == "undefined") return;

        menuText = $(menuTextNode[0]).text().replace(" ", "").toLowerCase();
        if (common.menuStates[menuText] == "down") return;

         //Following events are applied to the subnav itself (moving subnav up and down)  
         //$(this).parent().fadeTo(1, 0.75, null);
         common.menuStates[menuText] = "down";*/
         /*$(this).find("ul.subnav").slideDown('fast', function() {
            menuText = $(this).prev().text().replace(" ", "").toLowerCase();

            if (common.menuStates[menuText] == "down")
                common.menuStates[menuText] = "";
         }).show(); //Drop down the subnav on click  
         */

         totalHeight = 0;
         linkElements = $(this).find("ul a");
         //console.log(linkElements);
         for (iIterator = 0; iIterator <= linkElements.length - 1 ; iIterator++ )
         {
             totalHeight = totalHeight + parseInt($(linkElements[iIterator]).css("height").replace("px","")) + 3;
         }

         //$(this).find("ul.subnav").clearQueue();
         $(this).find("ul.subnav").stop(true).animate({ "height": totalHeight }, {duration: "fast", queue: false});
   
         //Following events are applied to the trigger (Hover events for the trigger)  
         }, function(e){
             //console.log($(this).parent().closest("li").find(e.relatedTarget));
             //console.log($(e.target).text() + " --> " + $(e.relatedTarget).text());
             if ($(this).hasClass("topnav") == true)
                 if ($.contains(this, e.relatedTarget) == true) return;
             else
                 if ($.contains($(this).parent().closest("li")[0], e.relatedTarget) == true) return;

             
             //$(this).find("ul.subnav").clearQueue();
             $(this).find("ul.subnav").stop(true).animate({ "height": 0 }, {duration: "slow", queue: false});
             //$(this).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
         }).hover(function() {  
             $(this).addClass("subhover"); //On hover over, add class "subhover"  
         }, function(){  //On Hover Out  
             $(this).removeClass("subhover"); //On hover out, remove class "subhover"  
     }); 
            
    $("#aMail").mouseover(function() {
        $("#imgMail").attr("src", "res/email_icon_highlight.png");
    });
    
    $("#aMail").mouseout(function() {
        $("#imgMail").attr("src", "res/email_icon.png");
    });
    
    $("#spanPhone").mouseover(function() {
        $("#imgPhone").attr("src", "res/icon_phone_2_highlight.png");
    });
    
    $("#spanPhone").mouseout(function() {
        $("#imgPhone").attr("src", "res/icon_phone_2.png");
    });
    
    $("#imgCaseStudies").mouseover(function() {
        $("#imgCaseStudies").attr("src", "res/btnSuccessHover.png");
    });
    
    $("#imgCaseStudies").mouseout(function() {
        $("#imgCaseStudies").attr("src", "res/btnSuccess.png");
    });
            
    $("ul.sf-menu").lavaLamp({ fx: "backout", speed: 700 });
    

    $("body").css("visibility", "");
    $("#content, #altContent").fadeIn(common.fadeInTime);
    
    common.onInitComplete();

    

});

