//Helper function for side nav - needs to be out here so setTimeout can see it
function IsNotCurrentPage(index){
    return !($(this).find(".currentitem").length > 0 || $(this).prev().hasClass("currentitem"));
}

//Main jQuery entry-point
$(document).ready(function() {
    //Fix IE6 png transparency
	$(window).load(function(){
	    $.ifixpng('/images/pixel.gif');
	    $("img[@src$=.png]").ifixpng();
	    if($.browser.msie && $.browser.version < 7){
	        $(".secondarynav")
	            .css("backgroundImage", "none")
	            .css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/images/translucent.png', sizingMethod='scale')");
	        $(".flatInfoShell .thirtyDay")
	            .css("backgroundImage", "none")
	            .css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/plans-and-prices/images/30day.png', sizingMethod='scale')");
	        $(".bubble>img").hide();
	        $(".bubble>div").css({backgroundImage: "none", padding: "12% 20px 20px"});
	        $(".bubble").css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/plans-and-prices/images/bubble_full.png', sizingMethod='scale')");
	    }
	});
	$('.userRow input').keyup(function(e) {
		if(e.keyCode == 13) {
			sidenavCalculator();				
		}
	});			
	$("#sideCalculateButton").click(function () {
		sidenavCalculator();				
	});	
	function sidenavCalculator(){
		//assumptions
		costOfLandLine = 60.00;
		usersPerLandLine= 2;
		longDistanceRate= .05;
		inboundTotalMinutes= .5;
		outboundLongDistance= .8;
		voipEnabledExtension= 5.00;
		
		totalMinutes = $("#employeesMinutes").val();
		inboundMinutes = totalMinutes * inboundTotalMinutes;
		outboundLocalMinutes = inboundMinutes * (1-outboundLongDistance);
		outboundLongDistanceMinutes = inboundMinutes * outboundLongDistance;
		
		totalUsers = $("#employeesNumber").val();
		landLines = Math.round(totalUsers / usersPerLandLine);
		costForStandardPhoneSystem = totalUsers * outboundLongDistanceMinutes * longDistanceRate + landLines * costOfLandLine
		
		//VPBX Flat-rate Plan Cost
		if (totalUsers<4){
			basePlan = 1;
			baseRate = 39.99;
			planId=13;
		}else if (totalUsers <9){			
			basePlan = 4;	
			baseRate = 95.96;
			planId=14;
		}else if (totalUsers <18){			
			basePlan = 10;		
			baseRate = 219.90;
			planId=15;
		}else if (totalUsers <45){			
			basePlan = 20;	
			baseRate = 399.80;			
			planId=16;
		}else{
			basePlan = 50;
			baseRate = 999.50;			
			planId=17;
		}
		if ((totalUsers - basePlan) < 0){
			extensions = 0;
		}else{
			extensions = totalUsers - basePlan;
		}
		extensionsCost = extensions * 24.99;
		totalVPBXFlatRateCost = baseRate + extensionsCost;
		flatSavings = costForStandardPhoneSystem - totalVPBXFlatRateCost;
		flatSavingsPercent = flatSavings/costForStandardPhoneSystem;
		
		//VPBX Usage-based Plan Cost
		totalMinutesInbound =  totalUsers * totalMinutes;

		if (totalMinutesInbound<531){
			plan = 5;
			planCost = 9.99;
			overateRate = .065;
			planId=3;
		}else if (totalMinutesInbound <944){			
			plan = 10;		
			planCost = 24.99;		
			overateRate = .058;
			planId=4;
		}else if (totalMinutesInbound <2063){			
			plan = 20;	
			planCost = 44.99;	
			overateRate = .047;			
			planId=5;
		}else{
			plan = 50;
			planCost = 94.99;
			overateRate = .044;
			planId=6;
		}
		if (totalMinutesInbound<300){
			overageMinutes = 0;
		}else if (totalMinutesInbound<531){
			overageMinutes = totalMinutesInbound - 300;
		}else if (totalMinutesInbound <944){			
			overageMinutes = totalMinutesInbound - 600;
		}else if (totalMinutesInbound <2063){			
			overageMinutes = totalMinutesInbound - 1000;
		}else{
			overageMinutes = totalMinutesInbound - 2500;
		}
		enabledExtensions = voipEnabledExtension * totalUsers;
		overageCost = overageMinutes * overateRate;
		totalVPBXSubUsageBasedCost = overageCost + planCost;
		costOfOutboundMinutes = totalUsers * outboundLongDistanceMinutes * longDistanceRate;
		totalVPBXUsageBasedCost = costOfOutboundMinutes + totalVPBXSubUsageBasedCost + enabledExtensions;
		usageSavings = costForStandardPhoneSystem - totalVPBXUsageBasedCost;
		usageSavingsPercent = usageSavings / totalVPBXUsageBasedCost;
		
		saveFromFlatRate = usageSavings - flatSavings;
		saveFromFlatRatePercent = saveFromFlatRate / totalVPBXFlatRateCost;
		
		if (saveFromFlatRate > 0){
			if (totalMinutesInbound<531){
				plan = 5;
				planId=3;
			}else if (totalMinutesInbound <944){			
				plan = 10;		
				planId=4;
			}else if (totalMinutesInbound <2063){			
				plan = 20;	
				planId=5;
			}else{
				plan = 50;
				planId=6;
			}
			 $(".calcHeader .planCell").text("Usage-based Plan");
			 $(".calcHeader .userCell").text("VPBX-"+plan);
			 $(".calcButtons .learnMore").attr("href", "/plans-and-prices/usage-based-plans.asp")
			 vpbxOverallCost = totalVPBXUsageBasedCost;

		}else{
			if (totalUsers<4){
				basePlan = 1;
				planId=13;
			}else if (totalUsers <9){			
				basePlan = 4;	
				planId=14;
			}else if (totalUsers <18){			
				basePlan = 10;		
				planId=15;
			}else if (totalUsers <45){			
				basePlan = 20;	
				planId=16;
			}else{
				basePlan = 50;
				planId=17;
			}
			$(".calcHeader .planCell").text("Flat-rate Plan");
			$(".calcHeader .userCell").text(basePlan + " User");
			 $(".calcButtons .learnMore").attr("href", "/plans-and-prices/flat-rate-plans.asp")
			 vpbxOverallCost = totalVPBXFlatRateCost;
		}
		$(".calcButtons .buyNow").attr("href", "https://osu.virtualpbx.com/loader.aspx?plan="+planId)
		$("#vpbxCost").text(vpbxOverallCost.toFixed(2));
		$("#tradCost").text(costForStandardPhoneSystem.toFixed(2));
		$("#dollarSavings").text((costForStandardPhoneSystem-vpbxOverallCost).toFixed(2));
	 	$("#percentSavings").text(Math.round(((costForStandardPhoneSystem-vpbxOverallCost)/costForStandardPhoneSystem)*100));
    }    
    //Overlays and helper functions for enlarging box behavior
    var vOverlay = {
        overlayImg: $("[src='/images/v_mouseover_big.jpg']"), 
        left: 0,
        top: 0,
        newLeft: 0,
        newTop: 0
    };
    
    var pOverlay = {
        overlayImg: $("[src='/images/p_mouseover_big.jpg']"), 
        left: 0,
        top: 0,
        newLeft: 0,
        newTop: 0
    };

    var bOverlay = {
        overlayImg: $("[src='/images/b_mouseover_big.jpg']"), 
        left: 0,
        top: 0,
        newLeft: 0,
        newTop: 0
    };

    var xOverlay = {
        overlayImg: $("[src='/images/x_mouseover_big.jpg']"), 
        left: 0,
        top: 0,
        newLeft: 0,
        newTop: 0
    };
    
    function enlargeSquareNav(overlay){
        overlay.overlayImg
            .css("left", overlay.left)
            .css("top", overlay.top)
            .css("width", 96)
            .css("height", 96)
            .css("display", "block")
            .animate({
                left: overlay.newLeft,
                top: overlay.newTop,
                width: 125,
                height: 125
            });
    }

    function shrinkSquareNav(overlay){
        overlay.overlayImg
            .animate({
                left: overlay.left,
                top: overlay.top,
                width: 96,
                height: 96
            }, {complete: function(){$(this).css("display", "none");}});
    }
    
    //Set up enlarging squares behavior
    $(".squarenav img").mouseover(function () {
        var offset = $(this).offset();

        if(!$(this).hasClass("squarenavoverlay"))
        {
            switch($(this).attr("src")) {
                case "/images/v_dim.jpg":
                    vOverlay.left = offset.left;
                    vOverlay.top = offset.top;
                    vOverlay.newLeft = offset.left - 29;
                    vOverlay.newTop = offset.top - 29;
                    enlargeSquareNav(vOverlay);
                    break;
                case "/images/p_dim.jpg":
                    pOverlay.left = offset.left;
                    pOverlay.top = offset.top;
                    pOverlay.newLeft = offset.left;
                    pOverlay.newTop = offset.top - 29;
                    enlargeSquareNav(pOverlay);
                    break;
                case "/images/b_dim.jpg":
                    bOverlay.left = offset.left;
                    bOverlay.top = offset.top;
                    bOverlay.newLeft = offset.left - 29;
                    bOverlay.newTop = offset.top - 1;
                    enlargeSquareNav(bOverlay);
                    break;
                case "/images/x_dim.jpg":
                    xOverlay.left = offset.left;
                    xOverlay.top = offset.top;
                    xOverlay.newLeft = offset.left;
                    xOverlay.newTop = offset.top;
                    enlargeSquareNav(xOverlay);
                    break;
            }
        }
    });
   
    $(".squarenav img.squarenavoverlay").mouseout(function () {
            switch($(this).attr("src")) {
                case "/images/v_mouseover_big.jpg":
                    shrinkSquareNav(vOverlay);
                    break;
                case "/images/p_mouseover_big.jpg":
                    shrinkSquareNav(pOverlay);
                    break;
                case "/images/b_mouseover_big.jpg":
                    shrinkSquareNav(bOverlay);
                    break;
                case "/images/x_mouseover_big.jpg":
                    shrinkSquareNav(xOverlay);
                    break;
            }
    });

    //Set up glow box behavior
    $(".sidesubnavitem").hover(
        function() {
            switch($(this).attr("id")) {
                case "sidesubnavitemred":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#FF4844"});
                    break;
                case "sidesubnavitemyellow":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#FFCD3B"});
                    break;
                case "sidesubnavitemgreen":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#B4E650"});
                    break;
                case "sidesubnavitemblue":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#00B4FE"});
                    break;
                case "sidesubnavitemlightblue":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#00B4FE"});
                    break;
            }
        },
        function() {
            switch($(this).attr("id")) {
                case "sidesubnavitemred":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#E82C2E"});
                    break;
                case "sidesubnavitemyellow":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#FDB813"});
                    break;
                case "sidesubnavitemgreen":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#A9CF3C"});
                    break;
                case "sidesubnavitemblue":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#0098D6"});
                    break;
                case "sidesubnavitemlightblue":
                    $(this).find(".hasBackgroundColor").andSelf().animate({backgroundColor: "#79B9D0"});
                    break;
            }
        }
    ).click(function(){
    	location.href = $(this).find("a").attr("href");
    }).corner();
	$(".featureButton").corner();
    //Fix glow box bug in which they move around on resize
    $(window).resize(function() {
        $(".sidesubnavitem").hide().show();
    });

    //Flag current page and open tertiary menu for side nav accordion initial state
    function CurrentPageFilter(){
        return $(this).find("a").filter(function(){
            if($(this).hasClass("multipage"))
                return location.pathname.indexOf($(this).attr("href")) == 0;
            else
                return location.pathname == $(this).attr("href");
        }).length > 0;
    }

    $(".tertiarysidenavmenu").hide();
    $(".secondarysidenavmenuitem")
        .filter(CurrentPageFilter)
        .addClass("currentitem")
        .next(".tertiarysidenavmenu")
        .show();
    $(".tertiarysidenavmenu>div")
        .filter(CurrentPageFilter)
        .addClass("currentitem")
        .parent()
	.show();

    //Side nav accordion behavior, accounting for missing tertiary menus
    $(".secondarysidenavmenuitem").hover(function(e){
        if($(this).next().hasClass("tertiarysidenavmenu"))
            $(this).next().siblings(".tertiarysidenavmenu").filter(IsNotCurrentPage).slideUp("fast");
        else
            $(".tertiarysidenavmenu").filter(IsNotCurrentPage).slideUp("fast");

        $(this).next().filter(".tertiarysidenavmenu").slideDown("normal");
    }, function(e){
    });

    var timeout = null;
    $(".secondarysidenavmenu").hover(function(e){
        if(timeout != null)
        {
            clearTimeout(timeout);
            timeout = null;
        }        
    }, function(e){
        timeout = setTimeout('$(".tertiarysidenavmenu").filter(IsNotCurrentPage).slideUp("fast")', 1000);
    });
    
    //Set up content-level accordions
    $(".compactaccordion").accordion({
        header: ".compactaccordionheader",
		active: false,
	    alwaysOpen: false,
        autoHeight: false
    });

    $(".contentaccordion").accordion({
        header: ".contentaccordionheader",
		active: false,
	    alwaysOpen: false
    }).bind("accordionchange", function(event, ui) {
        ui.oldHeader
            .find("[src='/services/images/arrowopen.png']")
            .attr("src", "/services/images/arrowclosed.png");

        ui.newHeader
            .find("[src='/services/images/arrowclosed.png']")
            .attr("src", "/services/images/arrowopen.png");
    });
    
    //Set up features pop-up bubble
    $("body:has(.features)").mousemove(function(event){
        var found = false;

        if(event.pageX >= $("#featurescontainer").offset().left && event.pageY >= $("#featurescontainer").offset().top)
            $(".features>div").each(function(){
                if(event.pageX > $(this).offset().left && 
                    event.pageX < $(this).offset().left + $(this).innerWidth() &&
                    event.pageY > $(this).offset().top &&
                    event.pageY < $(this).offset().top + $(this).innerHeight() &&
                    $(this).find(".bubbletext").text() != ""){
                        $(".bubble")
                            .css("left", $(this).offset().left)
                            .css("top", $(this).offset().top + 15)
                            .find("div")
                                .text($(this).find(".bubbletext").text())
                                .end()
                            .show(); //.fadeIn("fast");
                        found = true;
                    }
            });

        if(!found)
            $(".bubble").hide(); //.fadeOut("fast");
            
        event.stopPropagation();
    });
    
    //Set up product matrix slide panel
    $(".freetrial").click(function(){
        $(this).siblings(".freetrial").animate({backgroundColor: "#0098D6"});
        $(this).animate({backgroundColor: "#00B4FE"});
        $(".slidepanel").slideDown("normal");
        $("#freetriallink").attr("href", "https://osu.virtualpbx.com/Loader.aspx?plan="
                + $(this).attr("id").substr(9));
    });
    $(".usageInfoShell .freeTrial").click(function(){
        if ($(".slidepanel2").is(":hidden")) {
			$(".slidepanel2").slideDown("normal");
			$(this).addClass("selected");
		}else{
			$(".slidepanel2").slideUp("normal");
			$(".usageInfoShell .freeTrial").removeClass("selected");
		}
        $("#freetriallink").attr("href", "https://osu.virtualpbx.com/Loader.aspx?plan="
                + $(this).attr("id").substr(9));
    });

    //Add rounded top-left corner to topgreenseparator
    $("#topgreenseparator").corner({
        tl: { radius: 5 },
        tr: false,
        bl: false,
        br: false
    });

    //Set up tabs
    $(".imagetabs>ul,.tertiarytabs>ul").tabs({
        tabTemplate: '<li><a href="#{href}"><div>#{label}</div></a></li>'
    });
    
    //Add line on right of tertiary tabs
    $(".tertiarytabs>ul").each(function(){
        $(this).tabs("add", "#dummy", "&nbsp;");
        $(this)
            .tabs("disable", $(this).find("li").length - 1)
            .find("li")
            .eq($(this).find("li").length - 1)
            .find("div")
            .css("width", (635 - 96 * ($(this).find("li").length - 1)) + "px");
    });
	
	//Set up large tabs
    $(".imagetabs>ul,.tertiarytabslrg>ul").tabs({
        tabTemplate: '<li><a href="#{href}"><div>#{label}</div></a></li>'
    });
     //Add line on right of large tertiary tabs
    $(".tertiarytabslrg>ul").each(function(){
        $(this).tabs("add", "#dummy", "&nbsp;");
        $(this)
            .tabs("disable", $(this).find("li").length - 1)
            .find("li")
            .eq($(this).find("li").length - 1)
            .find("div")
            .css("width", (635 - 129 * ($(this).find("li").length - 1)) + "px");
    });  

    //Glow button click handlers
    $(".whatbutton").click(function(){ location.href = "/minisite.asp?section=whatisavpbx"; });
    $(".howbutton").click(function(){ location.href = "/minisite.asp?section=howdoesitwork"; });
    $(".whybutton").click(function(){ location.href = "/minisite.asp?section=whychoosevpbx"; });
    $(".helpbutton").click(function(){ location.href = "/minisite.asp?section=helpmechoose"; });
});
 
