var $j = jQuery.noConflict();
$j(document).ready(function() {
 $j("#bonus_popup").fancybox({
 	'padding': 30, 
	'overlayOpacity': 0.5,
 	'hideOnContentClick': false
 });

 $j("#testing").click(function(){
  $j("#advanced_search_form").append("<a class='map_popup' href='./?action=advanced_search_map'>Map</a>");
 });
 
 //##############################
 //## Anchor Array Specific JS ##
 //##############################
 
 table_width = $j("#stripe_table").width()
 $j("#az_anchor_array").css({'left': table_width + 60})
 
 //Grab the element for future reference
 $az_anchor_array = $j("#az_anchor_array")
 
 //Find the starting element offset
 var anchor_element_initial_offset = $az_anchor_array.offset()

 $j(window).scroll(function (){
	var anchor_element_initial_offset_top = anchor_element_initial_offset.top

	//Anchor Array height
	var anchor_array_height = $az_anchor_array.height()

	//Find the viewport height
  	var viewport_height = $j(window).height()
	
 	//Find the starting element offset
 	var anchor_element_offset = $az_anchor_array.offset().top
	
	//Find the current scroll offset
	var scroll_position = $j(window).scrollTop()

	//alert("Page Scroll Position = " + scroll_position);
	//alert("Element offset = " + anchor_element_offset);

	if(scroll_position > anchor_element_offset){
	 $az_anchor_array.stop().animate({'top' : scroll_position + ((viewport_height / 2) - (anchor_array_height + anchor_element_initial_offset_top))}, "fast")
	}else if ((anchor_element_offset - scroll_position) > (viewport_height - anchor_array_height) && scroll_position > anchor_element_initial_offset_top){
	 $az_anchor_array.stop().animate({'top' : scroll_position + ((viewport_height / 2) - (anchor_array_height + anchor_element_initial_offset_top))}, "fast")
	}else if (scroll_position < anchor_element_initial_offset_top){
	 $az_anchor_array.stop().animate({'top' : 0}, "fast")
	}
 })
 
 
 //Front page search redirect
 $j("#front_page_search").click( function() {
 //	location.href = 
 });


 //Load Suburbs when a state is selected
 $j("#search_state_select").change( function() {
 	$j("#postcode_input").val("");
	var current_type_selection = $j("input[name='type']:checked").val(); 
	var current_state_selection = $j("option:selected", this).attr("id");
 	if(current_state_selection != ""){
		$j.ajax({
			url: "./?action=advanced_search_load_suburbs&type="+current_type_selection+"&state="+current_state_selection,
			type: "GET",
			dataType: "html",
			beforeSend: function() {
				$j("#suburb_state_select").attr("disabled",true);
				$j("#suburb_state_select").html("<option>Loading Suburbs...<option>");
			},
			success: function(html) {
				$j("#suburb_state_select").html(html);
				$j("#suburb_state_select").attr("disabled",false)
			},
			error: function() {}
		});
	}else{
		$j("#suburb_state_select").html("<option>State Must Be Selected</option>");
		$j("#suburb_state_select").attr("disabled",true);
	}
 });

 //Restrict postcode input to numerals
 $j("#postcode_input").keydown(function() {
    	this.value = this.value.replace(/[^0-9\.]/g,'');
	var postcode_length = $j(this).val().length
 });

 //Load appropriate state and list of suburbs when a valid postcode is entered
 $j("#postcode_input").keyup( function() {
	var current_type_selection = $j("input[name='type']:checked").val(); 
    	this.value = this.value.replace(/[^0-9\.]/g,'');
	var postcode_length = $j(this).val().length
	if (postcode_length == 4){
		var current_postcode = $j("#postcode_input").val();
		$j.ajax({
			url: "./?action=advanced_search_load_postcodes&type="+current_type_selection+"&postcode="+current_postcode,
			type: "GET",
			dataType: "html",
			beforeSend: function() {
				$j("#suburb_state_select").attr("disabled",true);
				$j("#suburb_state_select").html("<option>Loading Suburbs...<option>");
			},
			success: function(html) {
					$j("#suburb_state_select").html(html);
					var postcode_state = $j("#suburb_state_select option").eq(0).attr("class");
					if(postcode_state != "error"){
						$j("#"+postcode_state).attr("selected", true);
						$j("#suburb_state_select").attr("disabled",false)
					}
			},
			error: function() {}
		});
	}
 });
 $j("#postcode_input").dblclick( function() {
 	$j(this).val("");
	alert(buildUrl())
 });

 //Clicking on a radio button label will tick the appropriate button
 $j(".radioset_type_label").click( function() {
 	$j(this).prev().attr("checked", "checked");
	});

 //Google maps initialisation 
 
    function initialize() {
      if (GBrowserIsCompatible()) {
        map.setCenter(new GLatLng(-27.997865, 153.418505), 13);
      }
    }
 
    function showAddress(shop_name, address) {
      map = new GMap2(document.getElementById("map_canvas"));
      geocoder = new GClientGeocoder();
      map.addControl(new GSmallZoomControl3D());
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              map.setCenter(point, 15);
              var marker = new GMarker(point);
              map.addOverlay(marker);
              marker.openInfoWindowHtml("<strong>"+shop_name+"</strong><br />"+address);
	      GEvent.addListener(marker, 'click', function(){
              	marker.openInfoWindowHtml("<strong>"+shop_name+"</strong><br />"+address);
	      })
            }
          }
        );
      }
    }
 


 //Load search results
 function buildUrl(type){
	var current_state_selection = $j("option:selected", "#search_state_select").attr("id");
	var current_suburb_selection = $j("option:selected", "#suburb_state_select").val();
	var current_postcode_selection = $j("#postcode_input").val();
	var current_type_selection = $j("input[name='type']:checked").val(); 
	var url_vars  = "./?action=advanced_search_load_results"
	    url_vars += "&type="+current_type_selection
	    url_vars += "&state="+current_state_selection
	    url_vars += "&suburb="+current_suburb_selection
	    url_vars += "&postcode="+current_postcode_selection

	    return url_vars;
 }
 
 $j("#load_search_results").click( function() {
 	$j.ajax({
		url: buildUrl(),
		type: "GET",
		dataType: "html",
		beforeSend: function() {
			$j("#advanced_search_results").html("");
			$j("#advanced_search_results").addClass("loading_results");
		},
		success: function(html) {
			
			function fillResultsDiv () {
				$j("#advanced_search_results").removeClass("loading_results");
				$j("#advanced_search_results").html(html);
			}
			//setTimeout(fillResultsDiv, 500)
			fillResultsDiv();
		        $j(".map_popup").bind("click", function() {
				$fancy_address = $j(this).parent().prev()
				 fancy_address = $fancy_address.text()
				 fancy_name = $fancy_address.prev().text();
			});		

  			$j(".map_popup").fancybox({
 	 			onStart: function(){
				},
				ajax : {
	 				type: "POST"
	 			},
				onComplete: function(){
					showAddress(fancy_name, fancy_address);
				}
 			 });





		},
		error: function() {}
	})
 })





});// end of $j(document).ready()

function reloadCorporateAccountReport(){
	startDate = document.getElementById('datepicker_start').value;
	endDate = document.getElementById('datepicker_end').value
	corporateAccountReportUrl = './?action=retailer_console_corporate&start_date=' + startDate + '&end_date=' + endDate;
	window.location = corporateAccountReportUrl;	
}


var timeout	= 100;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id, link){	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.display = 'none';
	if(ddmenuitem) ddmenulink.className = '';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenulink = document.getElementById(link);
	if(ddmenulink.style.display == '' ){
		ddmenuitem.style.display = '';
		}
	ddmenulink.className = 'selected';
	}
// close showed layer

function mclose(){
	if(ddmenuitem) ddmenuitem.style.display = 'none';
	if(ddmenuitem) ddmenulink.className = '';
	}

// go close timer
function mclosetime(){
	closetimer = window.setTimeout(mclose, timeout);
	}

// cancel close timer
function mcancelclosetime(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
		}
	}

// close layer when click-out
document.onclick = mclose;

/*var timeout	= 5;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id, link){	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.display = 'none';
	if(ddmenuitem) ddmenulink.className = '';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenulink = document.getElementById(link);
	if(ddmenulink.style.display == '' ){
		Effect.Appear(ddmenuitem, { duration: 0.4, queue: 'front'});
		}
	ddmenulink.className = 'selected';
	}
// close showed layer

function mclose(){
	if(ddmenuitem) Effect.Fade(ddmenuitem, { duration: 0.4, queue: 'end'});
	if(ddmenuitem) ddmenulink.className = '';
	}

// go close timer
function mclosetime(){
	closetimer = window.setTimeout(mclose, timeout);
	}

// cancel close timer
function mcancelclosetime(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
		}
	}

// close layer when click-out
document.onclick = mclose;*/


function clearInput(){
	pinInput = document.getElementById('recharge_pin');
	if(pinInput.value == 'Enter your pin number here') {
		pinInput.style.fontStyle = "normal";
		pinInput.style.color = "#666666";
		pinInput.value = '';
		}
	}

function checkClearInput(){
	if(pinInput.value == ''){
		pinInput.style.color = "#a4a4a4";
		pinInput.style.fontStyle = "italic";
		pinInput.value = 'Enter your pin number here';
		}
	}
function expandBrands(){
	myExpander = document.getElementById('quick_link_expander');
	if (myExpander.style.width == '235px'){
		myExpander.style.width = '18px';
		myExpander.innerHTML="";
		myExpander.style.backgroundImage= 'url(images/quick_links_expander.png)';
		}else{
		myExpander.style.backgroundImage= 'url(images/quick_links_expander_expanded_background.png)';
		myExpander.style.width = '235px';
		myExpander.innerHTML='<div style="float:left; width: 14px; height: 33px; background-image:url(images/quick_links_expanded_left.png);" ></div><div style="float:left"><a href="./?action=product_aussie_numbers">Aussie Phonecard</a>&nbsp;<a href="./?action=product_early_bird_numbers">Early Bird</a></div><div style="float:right; width: 15px; height: 33px; background-image: url(images/quick_links_expanded_right.png);"></div>';
	 	}
	}

function container_toggle(id){
	container = document.get_ElementById(id);
	
	}
