// JavaScript Document
var cache = []; // this must be cached as some browsers will 'forget' their cached images otherwise

function loadImage(path) {
    // Arguments are image paths relative to the current page.
    var cacheImage = document.createElement('img');
    cacheImage.src = path;
    cache.push(cacheImage);
}

function embedswf(){
	var flashvars = {};
	var params = {wmode:"transparent"};
	var attributes = {};
	swfobject.embedSWF("/swf/home-mobile.swf", "embed-swf?1234", "568", "388", "9.0.0","/swf/expressInstall.swf", flashvars, params, attributes);
}

function embedswf_newcustomer(){
	var flashvars = {clickTag:'http://www.orcon.net.nz/genius'};
	var params = {wmode:"transparent"};
	var attributes = {};
	swfobject.embedSWF("/swf/orc0027_homepage_660x385_clicktag.swf?5678", "embed-swf", "660", "385", "9.0.0","/swf/expressInstall.swf", flashvars, params, attributes);
}

function embedswf_existing(){
	var flashvars = {clickTag:'http://www.orcon.net.nz/genius'};
	var params = {wmode:"transparent"};
	var attributes = {};
	swfobject.embedSWF("/swf/orc0027_homepage_660x385_clicktag.swf?5678", "embed-swf", "660", "385", "9.0.0","/swf/expressInstall.swf", flashvars, params, attributes);
}

var mouseX = 0;
var mouseY = 0;

$(document).ready(function(){
    // fix pngs
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7)
        $(document).pngFix();
    // startup the banner rotator
    if ($(".jRotator").length)
        $(".jRotator").cycle({
            fx: 'cover',
            slideExpr: 'img',
            timeout: 7000,
            random: 1,
            pause: 0,
            direction: 'right'
        });
   
	//tweaked by MG to pass variable width and height of submenus
    $(".jMenu li").hover(

        function(e) {

			var menuId = $(this).attr("id");
			var options = null;
			var subMenu = null;
		
			switch (menuId) {

				case "idBusinessInternet":
					options = { selector: menuId, width: "479px", height: "100px" };
					break;

				case "idBusinessPhone":
					options = { selector: menuId, width: "479px", height: "130px" };
					break;

				case "idBusinessHosting":
					options = { selector: menuId, width: "479px", height: "285px" };
					break;
					
			}

			if (options != null) {
				subMenu = $("#"+options.selector).find(".jSubMenu");

				subMenu.stop()
					   .animate({ width: options.width, height: options.height, opacity: '1.0', overflow: 'auto' }, 150);				
			}            
        },
		function(e) {
			/* includes some ie6 hackery to prevent premature hiding
			on mouseout we check for position of mouse within the main submenu container, hiding it
			if only outside (or nearly outside) the bounds. Ignore top margin as that is where the
			parent menu item meets the submenu */
			if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
				var margin = 20;
				subMenu = $(this).find(".jSubMenu");
				var left = parseInt(subMenu.offset().left);
				var top = parseInt(subMenu.offset().top);
				var right = parseInt(left + subMenu.width());
				var bottom = parseInt(top + subMenu.height());
				if (e.pageX > (left + margin) && e.pageX < (right - margin) && e.pageY > top && e.pageY < (bottom - margin))
					return false;
			}			
			$(this).find(".jSubMenu")
				.stop()
				.animate({ width: '0px', height: '0px', opacity: 'hide' }, 300);
        }
    );


    // setup rollovers
    $(".jRollover")
        .each(function() {
            loadImage($(this).attr("src").replace(".", "_Over."));
        })
        .hover(function(e) {
            $(this).attr("src", $(this).attr("src").replace(".", "_Over."));
        }, function(e) {
            $(this).attr("src", $(this).attr("src").replace("_Over.", "."));
        });
    // background rollovers
    if (!($.browser.msie && $.browser.version.substr(0, 1) < 7))
        $(".jRolloverBackground")
            .each(function() {
                loadImage($(this).css("background-image").replace(".", "_Over."));
            })
            .hover(function(e) {
                $(this).css("background-image", $(this).css("background-image").replace(".", "_Over."));
            }, function(e) {
                $(this).css("background-image", $(this).css("background-image").replace("_Over.", "."));
            });


    if ($(".details").length) {
        $(".details").hide();
        $(".btnDetails").click(function() {
            $(this).parents(".styleBoxPlan").children(".details").slideToggle();
            $(this).toggleClass("seeOn");

        });
    }
    if ($(".lightbox").length) {

        $(".lightbox").hide();
        $("#login").hover(function() {
            $(".lightbox").fadeIn("slow");
			$("input[name='username']").focus();
			},
			  function() {
				  $(".lightbox").fadeOut("slow");
			  }
		);
    }


});


/* ======== Cosmos vs. Webmail Login ======== */

function loginToService(service)
{

	var postURL = '';

	switch(service){

		case 'cosmos':
		postURL = 'https://orcres.cosmos.net.nz/orconmembersarea.php';
		u_field = 'username';
		p_field = 'password';
		break;

		case 'webmail':
		postURL = 'https://mail.orcon.net.nz/portal/login.php';
		u_field = '_auto_username';
		p_field = '_auto_password';
		break;

	}

	if(postURL != ''){

		$("form#account").attr('action', postURL);
		$("#account_login_username").attr('name', u_field);
		$("#account_login_password").attr('name', p_field);

		if(service == 'webmail'){

			$("form#account").append('<input type="hidden" name="_webmail_client" value="2" />');

		}

		$("form#account").submit();

	}

}

function getIpBasedContent()
{

	$.get("/scripts/ipranges/check_ip.php", function(data){
  		if(data != ''){
			// Existing customer
			//$("#ipbasedcontent").html('<script>swfobject.embedSWF("/images/nobrainer/ORCON_existing.swf", "ipbasedcontent", "920", "175", "9.0.0", null, null, {"allowScriptAccess":"always","wmode":"transparent"});</script>');
			$.get('/site/customerpanel', function(data){ $("#ipbasedcontent").html(data) });

			//$("#dlife").removeClass('mTop10');

			embedswf_existing();

		}else{
			// New customer
			//$("#ipbasedcontent").html('<script>swfobject.embedSWF("/swf/home-joinus-banner-920x120.swf", "ipbasedcontent", "920", "120", "9.0.0", null, null, {"allowScriptAccess":"always","wmode":"transparent"});</script>');
			//$("#dlife").removeClass('mTop10');

			$("#purplebasebox").show();

			embedswf_newcustomer();
		}

	});

}

function getRandomPromo()
{

	$.get("/promo/random", function(data){
  		$("#promotile").html(data);
	});

}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

var navigation = {
    init: function() {
        navigation.login.init();
        navigation.search.init();
        navigation.menu.init();
        navigation.faq.init();
    },
    login: {
        storeBackground: function(element) {
          var bgImage = $(element).css('background-image');
          //alert(bgImage);
          $(element).data('bgImage', bgImage);
        },
        toggleBackground:  function(element) {
          $(element).keyup(function() {
            var bgImage = $(element).css('background-image');
            if ($(element).val() != '') {
              $(element).css('background-image', 'none');
            } else if (bgImage == 'none') {
              $(element).css('background-image', $(element).data('bgImage'));
            }
          });
        },
        init: function() {
           var accountInput = $('#account_login_username'),
               passwordInput = $('#account_login_password');
           if (accountInput.length > 0) {
                navigation.login.storeBackground(accountInput);
                navigation.login.toggleBackground(accountInput);
           }
           if (passwordInput.length > 0) {
                navigation.login.storeBackground(passwordInput);
                navigation.login.toggleBackground(passwordInput);
           }
        }
    },
    search: {
        hidesearchpanel: function() {
              var ss = $("#site-search"),
                overLink = $(ss).data('overlink'),
                overPanel = $(ss).data('overpanel'),
                showing = $(ss).data('showing');
              //window.console.log('showing: '+showing+', overlink: '+overLink+', overpanel: '+overPanel);
              if (showing && ! overLink && ! overPanel) {
                  $(ss).fadeOut(600);
                  $(ss).data('showing', false);
              } else {
                  setTimeout("navigation.search.hidesearchpanel()",2000);  // Reschedule.
              }
        },
        init: function() {


          $("#search-link").hover(function() {
             var ss = $("#site-search");
             $(ss).fadeIn(600);
             $(ss).data('overlink', true);
             $(ss).data('showing', true);
          },
          function() {
             $("#site-search").data('overlink', false);
             setTimeout("navigation.search.hidesearchpanel()",2000);
          });

          $("#site-search").hover(function() {
             $(this).data('overpanel', true);
          },
          function() {
             $(this).data('overpanel', false);
             setTimeout("navigation.search.hidesearchpanel()",2000); 
             $(this).data('overpanel', false);
          });
        }
    },
    menu: {
        init: function() {
           $("#menu ul li a,.menuSub li a").each(function() {
            // Don't add hover function for active link.
            var parent = $(this).parent();
            if (! $(parent).hasClass('active')) {
              $(this).hover(
                function () {
                  $(this).animate({ color: '#8c0479' }, 250);
                },
                function () {
                  $(this).animate({ color: '#162a63' }, 600);
                }
              ); // end hover
            } // end not active
          }); // end each
        }
    },
    faq: {
        init: function() {
            var $supportmain = $('#supportmain'),
                $gcswrapper = $('div.gsc-wrapper'),
                $supportsidenav = $('#supportmain').find('#supportSideNav'),
                $menuitems = $supportsidenav.find("#nav_categories").children();

            function displaySubMenuItem() {
              // Hide any results page, and reshow panels if hidden.
              $gcswrapper.hide();
              $supportmain.show();

              // Reset all submenu nav links.
              $('#menuSub li').removeClass('active');

              // Make this nav link active.
              $(this).parent().addClass('active');
            }

            // Set up display panel.
            $menuitems.children('a').bind("click",function(e) {
                e.preventDefault();
                //displaySubMenuItem();
                var $item = $(this).parent(),
                    $submenu = $item.children('ul');
                $item.toggleClass('active');
                if ($item.hasClass('active')) {
                    $submenu.slideDown();
                } else {
                    $submenu.slideUp();
                }
            });
        }
    }
}

var question = {
    init : function() {
        // Note: This requires scripts/plugins/plugins.js.
        /*
        $('a.question').tipsy({gravity: 's', offsetTop: 5, offsetLeft: 15}).bind("click",function(e) {
            e.preventDefault();
        });
        */
    }
}

$(document).ready(function() {
  navigation.init();
  //question.init();
});

