/* On DOM ready - this is where you execute your functions */
jQuery(function () {
    listDropdownSplit(jQuery(".nN-whiteStrip .hasDropdownSplit"));
    /* Closing dialog box */
    jQuery(".s-dialog .feSubmit input").click(function () {
        jQuery(".s-dialog").dialog('close');
    });

    /* Trigger datepicker */
    if (jQuery(".datepicker").length > 0) {
        jQuery(".datepicker").datepicker({
            showOn: "both",
            buttonImage: "",
            buttonImageOnly: false
        });
    }

    /* Calling functions */
    var cSuburbs = false
    jQuery("#cSuburbs").click(function () {
        if (cSuburbs == false) {
            cSuburbs = true
            jQuery("#selCity").fadeIn(1);
        } else {
            cSuburbs = false
            jQuery("#selCity").fadeOut(1);
        }
    });
    jQuery("#selCity").fadeOut(1);

    var sgMap = false
    jQuery("#cGoogleMap").click(function () {
        if (sgMap == true) {
            sgMap = false
            jQuery("#searchMap").fadeOut(1);
            jQuery("#cGoogleMap").text("Show Map");
        } else {
            sgMap = true
            initialiseSearchMap();
            jQuery("#searchMap").fadeIn(1);
            jQuery("#cGoogleMap").text("Hide Map");
        }
    });

    /* Calling functions */
    jQuery(".agentContacts").click(function () {
        jQuery(this).parent().children(".agentContactsPanel").slideDown();
    });

    jQuery("#l_buy").click(function () {
        jQuery("#l_lease").attr("checked", false);
    });
    jQuery("#l_lease").click(function () {
        jQuery("#l_buy").attr("checked", false);
    });
    jQuery("#s_buy").click(function () {
        jQuery("#s_lease").attr("checked", false);
    });
    jQuery("#s_lease").click(function () {
        jQuery("#s_buy").attr("checked", false);
    });

    jQuery("#selCity").fadeOut(1);
    jQuery(".agentContactsPanel").slideUp();
    jQuery("#searchMap").fadeOut(1);
    jQuery("#selCity").fadeOut(1);
    jQuery("a[rel*='print']").printDialog();
    jQuery(".jsPlaceholder").placeholder();
    jQuery(".s-tabs").tabs();
    jQuery(".accordion").accordion();
    jQuery(".s-rotator").rotator();
    jQuery(".jsCheckAll").checkAll();
    jQuery(".jsCheckNone").checkAll(); 
   // ToggleRefinements();

})

function ToggleRefinements() {
    if ($('otcLEASE').checked) {
        $('SaleType').hide();
        $('Occupancy').hide();
        $('AnnualReturn').hide();
        var offerTypes = $$('.offerType');
        for (var i = 0; i < offerTypes.length; i++) {
            $('ot' + offerTypes[i].value.replace("/", "")).checked = false;
        }
    }
    else {
        $('SaleType').show();
        $('Occupancy').show();
        $('AnnualReturn').show();
        //ensure the offer types are selected
        var offerTypes = $$('.offerType');
        for (var i = 0; i < offerTypes.length; i++) {
            $('ot' + offerTypes[i].value.replace("/", "")).checked = true;
        }
    }
}


/* Print Dialog function - you need rel="print" on the print link to trigger this */
jQuery.fn.printDialog = function() {
	var thisPrintLink = jQuery(this);
	jQuery.each(thisPrintLink, function() {
		jQuery(this).click(function() {
			window.print(); 
			return false;
		});
	});
}

/* Clear text input values */
jQuery.fn.placeholder = function() {
	var swapText = [];
	var placeholder = jQuery(this);
	
	jQuery.each(placeholder, function() {
	    swapText[jQuery(this).attr('id')] = jQuery(this).attr('value');
	    jQuery(this).bind('focus', function() {
	        if (jQuery(this).val() == swapText[jQuery(this).attr('id')]) {
				// add class for styling when user has entered text
				jQuery(this).addClass("jsPlaceholderFocus");
	            jQuery(this).val('');
	        }
	    });
	    jQuery(this).bind('blur', function() {
	        if (jQuery(this).val() == '') {
				jQuery(this).removeClass("jsPlaceholderFocus");
	            jQuery(this).val(swapText[jQuery(this).attr('id')]);
	        }
	    }); 
	});
}

/* Tab pages */
jQuery.fn.tabs = function() {
	var tabId;
	var thisTabPages = jQuery(this);
	var tabList = jQuery("ul.nav", this).attr({"role":"tablist"});
	var tabPanels = jQuery("div.tab", this).attr({"role":"tabpanel","aria-hidden":"true"});
	
	//For each tab
	jQuery("li > a", tabList).each(function(index) {
		// Get href of of tab list as tabs ID.
		tabId = jQuery(this).attr("href").slice(1);
		
		// Set aria and tabindex attributes. We also set the <li> to role presentation because in the tab structure the <li> is no longer a list but a tablist.
		jQuery(this).attr({"role":"tab", "aria-selected":"false", "tabindex":"-1"}).parent().attr({"role": "presentation"});
		
		// Pair up tab list and tab panels using aria-labelledby
		tabPanels.eq(index).attr("aria-labelledby", tabId);
	})
	// Set aria-selected to true for selected tab
	jQuery(this).find("li.selected a", tabList).attr({"aria-selected":"true", "tabindex": "0"});
	// Set aria-hidden to false for tab that's shown by default. Also set tabindex to 0 so user can tab into it. 
	jQuery(this).find("div.selected").attr({"aria-hidden":"false", "tabindex":"0"});

	
	jQuery("li > a", tabList).click(function() {
		var selectedTabId = jQuery(this).attr('href');
		// Set selected link as selected.
		jQuery('li > a[href=' + selectedTabId + ']', tabList).parents('ul').children().removeClass('selected').children("a").attr({"aria-selected":"false", "tabindex": "-1"});
		jQuery('li > a[href=' + selectedTabId + ']', tabList).parents('li').addClass('selected').children("a").attr({"aria-selected":"true", "tabindex": "0"});
		
		// Set selected tab as selected.
		jQuery('div.tab#' + selectedTabId, thisTabPages).parent().children("div.tab").removeClass('selected').attr({"aria-hidden":"true"});               
		jQuery('div.tab#' + selectedTabId, thisTabPages).addClass("selected").attr({"aria-hidden":"false", "tabindex":"0"});
		
		// Return false so the click doesn't scroll the page down.
		return false;
	});
	
	
	tabList.delegate("a", "keydown", function(e) {
		/* if left arrow key */
		if (e.keyCode == 37) {
			// If there's another list item before the selected tab
			if (jQuery(this).parent().prev().length != 0) {
				jQuery(this).parent().prev().children("a").focus().click();
			} else {
				// Reached the first tab, go select the last tab
				tabList.find("li:last > a").focus().click();
			}
		}
		/* if right arrow key */
		if (e.keyCode == 39) {
			// If there's another list item after the selected tab
			if (jQuery(this).parent().next().length != 0) {
				jQuery(this).parent().next().children("a").focus().click();
			} else {
				// Reached the last tab, go select the first tab
				tabList.find("li:first > a").focus().click();
			}
		}
	})

}



/* Accordion (uses Collabsible) */
jQuery.fn.accordion = function() {
	var accordion = jQuery(this),
		//allCollapsible = accordion.find(".ac-collapsible"),
		triggers = accordion.find(".ac-trigger");
		triggers.attr({"tabindex": "0"});
		
	// Collapse all collapsible containers in accordion by default
	jQuery("li", accordion).addClass('collapsed');
	
	jQuery(triggers).bind({
		'click': function(){
			triggerAc(this);
		},
		'keydown': function(event) {
			if (event.keyCode == '13' ) {
				triggerAc(this);
			};
		}
	});
	
	function triggerAc(trigger) {
		var	thisTrigger = jQuery(trigger);
		var collapsible = thisTrigger.parents("li");
		jQuery(collapsible).toggleClass('collapsed');
		
		// Collapse all collapsible containers in accordion that do not contain active trigger
		jQuery("li", accordion).not(collapsible).addClass('collapsed');
	}
}


/* Rotator - injecting the navigation */
jQuery.fn.rotator = function () {
    // check how many show cases we have
   
	/*
	 var count = jQuery("#showcaseCount").val();
	if (count <= 1) {
	    nav = '<ul class="rotatorNav"></ul>'
	}
	*/ 

    if (jQuery(".rotatorContent li").length > 1) {
	    var nav = '<ul class="rotatorNav"><li><a href="javascript:;" id="prev" rel="prev">Prev</a></li><li><a href="javascript:;" id="next" rel="next">Next</a></li></ul>'
	    jQuery('.rotatorContent', this).after(nav);
        jQuery('.rotatorContent').cycle({
            timeout: 5000,
            fx: 'fade',
            next: '#next',
            prev: '#prev'
        });
    }
}


/* Select / Deselect all checkboxes */
jQuery.fn.checkAll = function() {
	var allCheckbox = jQuery(".jsCheckFields")
	
	if (jQuery(this).hasClass("jsCheckAll")) {
		jQuery(this).click(function() {
			jQuery("input:checkbox", allCheckbox).attr('checked', true);
		});
	}
	
	if (jQuery(this).hasClass("jsCheckNone")) {
		jQuery(this).click(function() {
			jQuery("input:checkbox", allCheckbox).attr('checked', false);
		});
	}
}


/* - split list of links so that links marked with the class "more" appear in a 'More' drop-down
   - enable keyboard operation by listening for keyboard tabbing to the 'More' link */
function listDropdownSplit(list) {
	// we need a controller list item, which contains a 'More' link and an empty (nested) list to hold the contents of the dropdown
	var controller = jQuery('<li class="controller last"><a href="javascript:void(0);">More</a><ul></ul></li>'),
	// also need a reference to the document object
	doc = jQuery(document);
	// append the new controller to the end of the original list
	list.append(controller);
	// then append to the nested list within the controller all the items with the class "more"
	controller.children("ul").append(list.find(".more"));
	// define function to hide dropdown (once shown by keyboard operation)
	function closeDropdown() {
		controller.removeClass("focus");
		// once executed, unbind this handler from the window, as it is no longer required
		doc.unbind("click", closeDropdown);
	}
	// enable keyboard operability by adding class "focus" to show dropdown when keyboard tabs to the 'More' link
	controller.children("a").focus(function() {
		// check if the class "focus" already exists before running this function, because the user may have tabbed into the dropdown and then back to the controller link (in which case the dropdown will still be active)
		if (controller.hasClass("focus")) return;
		controller.addClass("focus");
		// then bind handler to watch for click event to close dropdown
		doc.click(closeDropdown);
		// also listen for keyboard tabbing beyond the last list item
		controller.find("li:last-child a").blur(closeDropdown);
		// as well as keyboard tabbing back beyond the controller to the previous item
		controller.prev().find("a").focus(closeDropdown);
	});
	// enable hover states in IE 6 (as it doesn't support li:hover CSS)
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		controller.hover(
			function() { controller.addClass("hover") },
			function() { controller.removeClass("hover") }
		);
	}
	// attach class to indicate script has executed
	list.addClass("scripted");
}

/* The code below are taken from Media's fd.js. These functions are required for the gallery. */
/**
 * Tracks a page impression with Nielsen.
 */
var doNielsenPageImpression =  function() {
    if (typeof(trac) != "undefined") {
        var pageName;
        if (window.s_pageName) {
            pageName = window.s_pageName;
        } else {
            if (window.s) {
                pageName = window.s.pageName;
            }
        }
        if (pageName) {
            trac.pageEvent(pageName);
        }
    }
}

/**
 * Stops the propagation and default action of an event.
 *
 * @param e The event object.
 */
var stopEvent = function(e) {
    e.stopPropagation();
    e.preventDefault();
}

/**
 * Returns the calculated elements left position.
 * <p/>
 * Unfortunately we cannot use <code>element.position().left</code> as for some reason IE seems to lose 1px
 * each time a change is made to the left position.
 *
 * @param element Element to calculate left position of.
 * @return Calculated content table position.
 * @private
 */
var calculateElementLeftPosition = function(element) {
    var elementLeftPositionString = element.css("left").replace(/px/ig, "");
    var elementLeftPosition = parseInt(elementLeftPositionString);
    if (isNaN(elementLeftPosition)) {
        return 0;
    }
    return elementLeftPosition;
}

var geocoder;
var map;var bounds
  
function initialiseSearchMap() {

    geocoder = new google.maps.Geocoder();
    
    // get the first suburb name listed next to the property count 
    var address = jQuery(".searchedSuburbs").text().split(',')[0].trim() + ", Australia";
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latlng = results[0].geometry.location;
            var myOptions = {
                zoom: 12,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            bounds = new google.maps.LatLngBounds(latlng, latlng);
              map = new google.maps.Map(document.getElementById("gMap"), myOptions);

            // loop through all of the listing addresses stored on the page and load each one on the map
            jQuery(".s-listing").each(function () {
                var coords = jQuery(this).children(".Address").val();
                AddAddressToMap(coords);
            });

        }
    });

   
}

function AddAddressToMap(coords) {

    var long = coords.split(',')[0].trim();
    var lat = coords.split(',')[1].trim();
    var latlng = new google.maps.LatLng(long, lat);
    var marker = new google.maps.Marker({
        position: latlng,  
        map: map
    });
    bounds.extend(latlng); map.setCenter(bounds.getCenter());
}
