$(document).ready(function(){
  
  //colorbox for Product Demo page
  $(".demo-video").colorbox({iframe:true, innerWidth:560, innerHeight:450});
  
  // Calculate total Training Units price
  function refreshTotal() {
    var unitPrice = 0;
    var amount = $('#q7994_q5').val(); 
    if(amount < 10){
      unitPrice = 400;
    }
    if(amount > 9 && amount < 25){
      unitPrice = 380;
    }
    if(amount >= 25){
      unitPrice = 360;
       }
    var total = amount * unitPrice;
    $("#tu-total").html('costing $' + total + ' (excl GST)');
  }

  $('#q7994_q5').change(function() {
    refreshTotal();
  });

  // Enable previous and next buttons
  prevNext();

  // Add focus and blur classes
  focus();

  // Add training defaults
  if($('#page1646').length > 0){
       training()
  }

  // Enquiry Form Improvements
  if($('#page7370').length > 0){
      enquiryFormControls();
  }

  // General Contact Form Improvements
  if($('#page7370, #page7400').length > 0){
       generalForm();
  }

  //Event rego
  if($('#page9159').length > 0){
       autoPopulateRego();
  }


  if($('#page6643')){
       glorifyProductsSuiteTable();
  }

  // Create newsletter anchor links
  if ($("body.newsletter").length > 0) {
    createNewslettersAnchorLinks();
  }

  if ($("#page4644, #page4622").length > 0) {
    $('.seminar-cms .seminar-location').click(function(){
      $('.seminar-cms').fadeOut(function(){
        $(this).html('<h2>Prefered Location</h2><p>The MySource Matrix Enterprise CMS seminar is held in Wellington as well as in Auckland. Please select your prefered location:</p><ul><li><a href="./?a=4451">Auckland Tue 17 Nov</a></li><li><a href="./?a=2614">Wellington Wed 18 Nov</a></li></ul>').fadeIn();
      })
      return false;
    })

    $('.seminar-funnel .seminar-location').click(function(){
      $('.seminar-funnel').fadeOut(function(){
        $(this).html('<h2>Prefered Location</h2><p>The Funnelback Enterprise Search seminar is held in Wellington as well as in Auckland. Please select your prefered location:</p><ul><li><a href="./?a=4684">Auckland Tue 17 Nov</a></li><li><a href="./?a=4144">Wellington Wed 18 Nov</a></li></ul>').fadeIn();
      })
      return false;
    })
  }

  if ($(".pageid_4144").length > 0) {
    $('#q4145_q10 option[value*=' + $(document).getUrlParam("location") + ']').attr('selected', 'selected');
  }

  //HP styles
  if($('#hp-scroller').length > 0){
     hpScroller();
  }
  if($("#hp-twitter").length > 0) {
     getMeTweeties();
  }

  //load superfish
  $('ul#nav').supersubs({
    minWidth:    8,   // minimum width of sub-menus in em units
    maxWidth:    20,   // maximum width of sub-menus in em units
    extraWidth:  1     // extra width can ensure lines don't sometimes turn over due to slight rounding differences and font-family
  }).superfish({ 
    animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
    speed:       'fast',                          // faster animation speed 
    autoArrows:  false,                           // disable generation of arrow mark-up 
    dropShadows: false                            // disable drop shadows 
  });


  // Resources
  resources();

  // Set search box radio buttons based on what is in the query string paramters of the url
  if ($("#search-results-form").length) {

    // Use the hidden 'scope' field to see which button was selected when the form was last submitted
    var scope = $("#scope").attr("value");
    if (scope == "www.squiz.co.nz") {
      $("#local").attr("checked", "checked");
    } else {
      $("#world").attr("checked", "checked");
    }
  }

  // Tidy up search results navigation - remove unwanted next/prev links, and the whole search results nav if there is only one page
  if ($("#search-results-nav").length) {
    $("#search-results-nav").contents().not($("#search-results-nav").children()).remove();

    if (!$("#search-results-nav a").length) {
      $("#search-results-nav").remove();
    }
  }

  // Change region time for Webinar 19 Oct - Willy
  if ($("#page8896").length){
    $("#RegistrantTimeZoneKey").attr("value","3")
  }

  $(document).addGADownloadTracking();

});


/* Makes some non-essential prettifications on the Resources page - ck 19 july 2010*/
function resources() {
  if ($("#page6282").length > 0) {
    // Make lis clickable for expected behaviour, also hide links offscreen
    $('#page-resources ul li').each(function(){
    var a = $(this).find('a');
    $(this).bind('click', function(){
        top.location.href = a.attr('href'); 
    });
    a.not('.nohide').css({
        'position'  : 'absolute', 
        'left'      : '-999px'
    });
        $(this).css("cursor", "pointer")
    });
  
    // Make boxes same height
    $('#page-resources ul').each(function(){
    var height = 0;
        $(this).find('li').each(function(i){
            if($(this).height() > height) {
                height = $(this).height();
            }
        })
        $(this).find("li").height(height);
     });
  };
}; /* End Resources */

/* Prefer phone contact functionality - implemented to keep form size to a minimum for conversion improvements */
function enquiryFormControls() {
    $("#enquiry-phone")
    .hide()
    .prev('div')
    .find('input')
    .after('<a id="prefer-phone">I prefer to be contacted by phone</a>');

    $("#prefer-phone").click(function() {
        $(this).fadeOut("fast", function(){
            $("#enquiry-phone").fadeIn("fast", function(){
         $(this).css({ /* IE ClearType whackyness fix */
                  'filter' : '',
                  'width' : '100%'
               }); 
            });
        });
        
     });

    if($('#form-errors li')){ $('#form-errors').addClass('active') }

    // select all desired input fields and attach tooltips to them
   $("#form_email_7371 :input").tooltip(
      {
  position: "top right",
  offset: [24, 10],
  opacity: 0.8
       }
   );


} /* /enquiryFormControls */

/* General Form controls */
function generalForm() {

       if($('#form-errors li').length > 0){ $('#form-errors').addClass('active') }

    // select all desired input fields and attach tooltips to them
   $("#main_content :input").tooltip(
      {
  position: "center right",
  offset: [0, 10],
  opacity: 0.9
       }
   );


} /* /traininForm */

function training() {

    if ($(".pageid_1646").length > 0) {
      $("#q1647_q17").val($(document).getUrlParam("course").replace(/%20/g," "));
      $("#q1647_q15").val($(document).getUrlParam("date").replace(/%20/g," "));
      $("#q1647_q16").val($(document).getUrlParam("location").replace(/%20/g," "));
    }

}; // end of training()

function navAnimation() {

  $('#region_nav a').hover(function() { //mouse in  
    $(this).animate({ paddingTop: '10px', paddingBottom: '2px' }, 300);  
  }, function() { //mouse out  
    $(this).animate({ paddingTop: '2px', paddingBottom: '10px' }, 300);  
  });

}; // end of navAnimation()

function prevNext() {

    $("#page_nav .nojs").fadeOut("def", function() {
      $("#page_nav .js").fadeIn("def");
    });

    var total_news_items = $(".jsLoad div").length;
    var news_item_shown = 1;

    $("#page_nav .prev").click( function() {
       if (news_item_shown > 1) {
          $("#news_"+news_item_shown).fadeOut("def", function() {
             news_item_shown = news_item_shown -1;
             $("#news_"+news_item_shown).fadeIn("def");
          });
        }
       return false;
    });

    $("#page_nav .next").click( function() {
       if (news_item_shown < total_news_items) {
          $("#news_"+news_item_shown).fadeOut("def", function() {
             news_item_shown = news_item_shown +1;
             $("#news_"+news_item_shown).fadeIn("def");
          });
        }
       return false;
    });

}; // end of prevNext()

function focus() {

    $("*:input").focus(function () {
      $(this).addClass("focus");
    });
    $("*:input").blur(function () {
      $(this).removeClass("focus");
    });


}; // end of focus()


function createNewslettersAnchorLinks() {

  // Going through the page content and give all the h2 headings an id
  var anchorNo = 1;
  $("#main_content h2").each(function() {
     $(this).attr("id", "a" + anchorNo++);
  });

  // Loop through the h2s in the content and construct an anchor link for each
  var h2Id;
  var h2Text;
  var ulString = "<ul>";

  $("#main_content h2").each(function () {
      h2Id= $(this).attr("id")
      h2Text= $(this).text();
      ulString = ulString + '<li><a href="#'+ h2Id + '">' + h2Text + '</a></li>';
  });

  ulString=ulString + "</ul>";
  $("#anchor-links").html(ulString);

} // createNewslettersAnchorLinks


//Makes a prettier Squiz Suite table on products page
function glorifyProductsSuiteTable(){
   $('.suite-product, #suite-table-intro').each(function(){
    
      $(this).append('<div class="suite-overlay hide"><a href="' + $(".suite-product-link", this).attr("href") + '">' + $(".suite-product-link", this).attr("title") + '</a></div>')
      
      $('.suite-overlay > a', this).css("line-height", $(this).height() + 15 + "px");
      
      $(this).hover(
        function()
          {
            $('.suite-overlay', this).fadeIn("fast")
          },
        function()
          {
            $('.suite-overlay', this).fadeOut("fast")
          }
      
      )
    
    })
} //glorifyProductsSuiteTable

/* Shiny HP Scroller */
function hpScroller() {
  $("#hp-scroller-controls").addClass('js').fadeTo('fast', 0.6);
  $("#hp-scroller-controls").hover(
    function() {
      $(this).fadeTo('fast', 1)
    },
    function() {
      $(this).fadeTo('fast', 0.6)
    }
  )
  
  
  $("#hp-scroller").scrollable(
    {
      circular: true, 
      mousewheel: true,
      prev: "#hp-scroller-prev",
      next: "#hp-scroller-next"
    }).navigator(
    {
      navi: "#hp-scroller-navi"
    })
    
    /* Uncomment the following section to reenable autostart
    .autoscroll(
    {
      interval: 5000    
    }); 
    */
}
/* /Shiny HP Scroller */

/* Loads the latest Tweets onto the HP */
function getMeTweeties() {

	//make that datestamp a little prettier
	function parseTwitterDate(stamp)
	{        
	// convert to local string and remove seconds and year // 
	    var now = new Date();
	    
	    stamp = stamp.substr(0,30).split(' ');	    
		var postedDate = new Date(Date.parse(stamp[1]+" "+stamp[2]+", "+stamp[5]+" "+stamp[3]+" UTC"));
		
		
		var timePassed = Math.ceil(now.getTime()-postedDate.getTime()) / 1000 / 60;
						
		if (Math.round(timePassed) < 60) {
				
			if (Math.round(timePassed) < 1) {
				timePassed = "less than 1 minute ago" 
			} else if (Math.round(timePassed) == 1) {
				timePassed = "one minute ago";
			} else {
				timePassed = Math.round(timePassed) + " minutes ago";
			}
						
		} else if (Math.round(timePassed / 60) < 24) {
			
			timePassed = Math.round(timePassed / 60);
			
			if(Math.round(timePassed) > 1) {
				timePassed = timePassed + " hours ago" 
			} else {
				timePassed = "1 hour ago" 
			}
			
		} else if (Math.round(timePassed / 60 / 24) == 1){
		
			timePassed = " yesterday"
			
		} else {
		
			timePassed = Math.round(timePassed / 60 / 24) + " days ago"
		
		}
				
		return "Tweeted " + timePassed;
		
	}
	
	$("#hp-twitter").append('<h2><a href="http://twitter.com/squiznz" title="Goto the Squiz NZ twitter page">Latest @squiznz tweets</a></h2><div id="twitter-loader">Getting latest tweet...</div>');
	$('#twitter-loader').slideDown();
	

    	$.ajax({
            type: "GET",
            url: window.location.protocol + '//' + window.location.hostname + '/_designs/design_helpers/twitter/tweets',
	    dataType: ($.browser.msie) ? "text" : "xml", /* Load appropriate dataTYpe for IE, see http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests */
            success: function(xml){
                 /* Ensure we have an xml object in IE */
                 if (typeof xml == "string") {
                   data = new ActiveXObject("Microsoft.XMLDOM");
                   data.async = false;
                   data.loadXML(xml);
                 } else {
                    data = xml;
                 }

	        	$('#twitter-loader').after('<div id="tweet"><p id="tweet-text">' + $(data).find("text").text() + '</p><p id="tweet-date">' + $(data).find("date").text() + '</p>');
	        	$('#tweet').slideUp(0);
	        	
	        	//Relink Urls - twitter only sends out plain text
				$('#tweet-text').html($('#tweet-text').html().replace(/(http(|s):\/\/[a-zA-Z0-9.\/-\?]+)/gi, '<a href="$1">$1</a>'));
				
				//Relink Mentions - twitter only sends out plain text
				$('#tweet-text').html($('#tweet-text').html().replace(/\@([a-zA-Z0-9.\/-\?]+)/gi, '<a href="http://www.twitter.com/$1">@$1</a>'));
			
				//Clean up that datestamp
				$('#tweet-date').text(parseTwitterDate($('#tweet-date').text()))
			
				var spec = $(data).find("id").text();
				spec = spec.substr(0, spec.indexOf(',')).split('|');
				$('#tweet-date').html('<a href="http://www.twitter.com/' + spec[0] + '/status/' + spec[1] + '">' + $('#tweet-date').text() + '</a>');				
				$('#twitter-loader').slideUp(function(){
					$(this).remove();
					$('#tweet').slideDown();
				})
	   },
           error: function(a, b, c){
	    		
				$('#twitter-loader').html("<p>Ooops, we are having problems getting the latest tweet.<br /> I will close now.</p>")

				//Need some error notification to sysadmins here maybe?
				
				var t = setTimeout("$('#twitter-loader').prev('h2').andSelf().slideUp(function(){$(this).remove();})",5000);
	    }
	})
	
} /* /getMeTweeties() */

  // General Contact Form Improvements
  if($('#page254').length > 0){
$.getScript('http://konami-js.googlecode.com/svn/trunk/konami.js', function(data, textStatus){
    konami = new Konami();
    konami.code = function() {
        $.colorbox({html:'<h1 style="line-height:320px;text-align:center;text-decoration:blink;color:#0f0;background:#000;font-family:monospace;font-size:2.5em; ">You Win!!!</h1>', innerWidth:420, innerHeight:345})
        var t=setTimeout("$.colorbox({iframe:true, innerWidth:420, innerHeight:345, href:'http://sebleedelisle.com/games/moonlander/MoonLander.swf'});",3000);
    }
    konami.load();
});
  }


//Auto populate rego form
function autoPopulateRego(){

    var hash = window.location.hash
    
    switch(hash.substring(hash.indexOf("/r/")+3, hash.indexOf("/r/") + 7))
    {
        case "9083":
            $("#q9160_q6_0").attr("checked", "checked");
            break;

        case "9087":
            $("#q9160_q6_1").attr("checked", "checked");
            break;

        case "9136":
            $("#q9160_q6_2").attr("checked", "checked");
            break;
    } 

}

