$(function () {
	
	siteUi.init();
	//navUi.init(); // initiate functionality of primary nav and sidebar nav
	
	if ($("#prx-master").is('*')) {
		$('#prx-master').prxInit($('#home-scrollbar'), 980, 1280); 
	}
	if ($("#roaming_widgetPage").is('*')) roamingUi.init(); // if roaming page
	if ($("#locator_widget").is('*')) storeUi.init();
        
        
        $("#acc_type").change(function (){

            if($(this).val()=='Account') {

                $("#old_acc_number").show();
                $("#sinm_number").hide();
            }else{
                $("#sinm_number").show();
                $("#old_acc_number").hide();
            }
            return
        })
});

/* Primary and sidebar navigation */
navUi = {
	init : function () {
		
		/* slide down corresponding list (ul) */
		$('#sidebar-nav #master-list .level2 a').click(function(){
			var rel = $(this).attr('rel');
			if(rel !== undefined)
			{
				$('#sidebar-nav #master-list #'+rel).slideToggle('fast');
				$(this).toggleClass('current');
			}
		});
                
		/* Show sub menu */
		var subNav = $('#submenuBar'),
			overPrimaryItem = false,
			navTarg,
			subNavTimeout,
			hideNav;
		
		$('#header-nav a.primary-nav').hover(
			function(){
				navTarg = $(this);
				clearTimeout(subNavTimeout);
				clearTimeout(hideNav);
				
				/* Delay on show */
				subNavTimeout = setTimeout(function(){
					var sub = $(navTarg).attr('rel');	
					$('.sub-nav-menu').hide();
					$('#submenuBar #'+sub).show();
					subNav.show();
					overPrimaryItem = true;
				}, 500);
			},
			function(){
				overPrimaryItem = false; // Mouse out primary nav
				clearTimeout(subNavTimeout);
				clearTimeout(hideNav);
			}
		);
			
		$(subNav).hover(
			function(){
				clearTimeout(subNavTimeout);
				clearTimeout(hideNav);
			},
			function(){
				if(!overPrimaryItem){
 					hideNav = setTimeout(
 						function(){ 
 						if(!overPrimaryItem){
 							$('.sub-nav-menu').hide();
							subNav.hide();
						}
					},900);
				}
			}
		);

		/* Login form - placeholder functionality */
		if(!Modernizr.input.placeholder){
			
			$('input.login_number').val($('input#login_number').attr('placeholder'));
			$('input.login_password').val($('input#login_password').attr('placeholder'));
			
			/* Focus events */
			$('.login_form input').focus(function(){
				if($(this).val() === $(this).attr('placeholder'))
				{
					$(this).val('');
					$(this).removeClass('placeholder');
				}
			});
			$('.login_form input').focusout(function(){
				if($(this).val() === '')
				{
					$(this).val($(this).attr('placeholder'));
					$(this).addClass('placeholder');
				}
			});
		}
		
	} // end init
} // end navUi

siteUi = {
	init: function (){
		 
		$('.helpTitle h3 a').addClass('catBGup'); 
		$('li.helpTitle').hover(
			function () {
				if( $('ul.dropDown li', this).size() > 0){
					$('h3.catTtl a', this).addClass('catBGdown');
					$('ul.dropDown', this).stop(true, true).slideDown(250);
				}
			},
			function () {
					$('ul.dropDown' , this).stop(true, true).slideUp(250);
					$('h3.catTtl a', this).addClass('catBGup');
					$('h3.catTtl a', this).removeClass('catBGdown');
			}
		);	
		
		$('.query').click(function(){
			var PU_btn = document.getElementById('query');
			var articleID = PU_btn.getAttribute('data-kb-article-id');
			var KBsrc = 'https://skny.custhelp.com/app/answers/popupdetail/a_id/';
		    var iframeSRC = KBsrc.articleID;
			$('.helpPopUp').show();
			$('#pop_up_content').show();
			return false;	
		});
		$('#close').click(function(){
			$('#pop_up_content').hide(100);
			$('.helpPopUp').hide(500);
		});
		
		/* Fullscreen background scaler */
		var theWindow = $(window);
		var $bg = $("#bg");
		$('#background').show();
		var aspectRatio = $bg.width() / $bg.height();
		var container_height = $('#container').height();
		$('#background').height($('#container').height());

		function resizeBg() {
			var orientaion = (theWindow.height() > theWindow.width()) ? 'portrait' : 'landscape';
			var scale = true;
			if(orientaion === 'portrait' && scale){ // scale width
		  		var new_height = theWindow.height();
		  		var new_width = Math.round(new_height*aspectRatio);
		  	}else{
		  	 	var new_width = theWindow.width(); // scale height
		  		var new_height = Math.round(new_width/aspectRatio);
		  	}

	  		/* Make sure new dimensions fill the parent div */
	  		if(new_height >= container_height && new_width >= theWindow.width()){
	  			$($bg).width(new_width+'px');
	  			$($bg).height(new_height+'px');
	  		}
		}
		/* Initial resize */
		setTimeout(function(){ 
			resizeBg();
			
			if($bg.hasClass('login_background'))
			{
					
			}else{
				$bg.css('width', 'auto');
			}
		}, 700);
		
		/* tabs for product pages */
		if($('.tabbed-content').length>0){
			$('.tabbed-content').wrap('<div class="tabbed-wrapper" />').tabs({
				fx: {
					'opacity': 'toggle'
				},
				cookie: {
					expires: 30
				}
			});
		}

		/* Globale input styles */
		$('input:radio').screwDefaultButtons({
			checked: 	"url(./img/radio_Checked.png)",
			unchecked:	"url(./img/radio_Unchecked.png)",
			width:		85,
			height:		85
		});
		$('input:checkbox').screwDefaultButtons({
			checked: 	"url(./img/formBoxCheck.png)",
			unchecked:	"url(./img/formBoxUncheck.png)",
			width:		85,
			height:		85
		});
		
		// open login  window
		$('a#open-login-modal').click(function (e) {
			e.preventDefault();
			target = '.modal-window#';
			target += $(this).attr('data-page');
			$(target).lightbox_me({
				overlayCSS: {
					background: 'black',
					opacity: .50
				},
				modal: false,
				pos: {
					x: '50%',
					y: '40px'
				},
				onLoad: function () {
					$(target).find('input:first').focus()
				}
			});
		});

		if($('.datepicker').length>0) {
		
			// setup date-range datepicker
			$(".datepicker").datepicker({
				'defaultDate': +1,
				'autoSize': true,
				'dateFormat': 'dd / mm / yy',
				'yearRange': '-100:+100',
				'changeYear': true,
				'showOn': 'focus',
				'buttonImageOnly': true
			});
			// setup form date picker
			$(".vForm #shift-date input[type=text].datepicker").datepicker({
				'defaultDate': +1,
				'minDate': '0d',
				'maxDate': '+30d',	
				'autoSize': true,
				'dateFormat': 'dd / mm / yy',
				'yearRange': '-100:+100',
				'changeYear': true,
				'showOn': 'focus',
				'buttonImageOnly': true
			});
		}
			
		// style select controls
		$('select').selectBox({
			menuTransition: 'slide',
			menuSpeed: 'fast',
			useJScrollPane: true
		});

		// handler for groups of radio button and checkbox form controls
		$('.group input:checked').parent('label').addClass('selected');
		$('.group input[type=radio]').click(function () {
			$('.group label input[type=radio]').parent().removeClass('selected');
			$(this).parent('label').addClass('selected');
		});
		$('.group input[type=checkbox]').click(function () {
			$(this).parent('label').toggleClass('selected');
		});
		// zebra stripes for tables
		$("table.stripe tr:nth-child(odd)").addClass("odd");
		// top-up payment page - select page for iframe (payment type)
		$('#selectPaymentType input[name=pay-type]').change(function () {
			var tmp = $(this).val();
			$('#payment-frame').attr('src', tmp);
		});
		
		$('.modal-window button[type=submit]').click(function () {
			$('.modal-window').trigger('close');
		})
		//$('.vForm span.validation-msg').css('display', 'none');
		$('.vForm ').toggleClass('validation-failed', false);
		$('button[type=submit]').click(function (ev){
			// $(this).parents('.vForm').find('.rqd').toggleClass('validation-failed');
			// $(this).parents('.vForm').find('span.validation-msg').toggle('fast');
			// ev.preventDefault();
		});
		
		/* A single window resize listener */
		$(window).resize(function(){
			resizeBg();
			$('select').selectBox('hide');
		});
	}
} // siteUi

/*Roaming UI*/
roamingUi = {
	init : function () {
			
	google.setOnLoadCallback(init);
	var dataSourceUrl = 'https://docs.google.com/spreadsheet/pub?tq?tqx=out:json&key=0AjIBBUEaN9YndFVuSV84MGpNY1NkdDF2b1ZXSHIwVGc';
	var query;
	var countryIndex = Array();
	var numCountries = 0;
	var data; // Very important - holds all table data!!! 
	$('#select_all_countries').find(':checkbox').attr('checked', true);
	
	/* Called once Google is good and ready */
	function init() {
		$('#widget_msg').html('Preparing the countries list...');
		query = new google.visualization.Query(dataSourceUrl);
		query.send(handleQueryResponse);
	}
	/* Called when the query response is returned. */
	function handleQueryResponse(response) {
	 if (response.isError()) {
		alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); //TODO: Style this message?
		return;
	  }else{
		data = response.getDataTable();
		createCountrySelect();//<--- Next step, mess with the DOM
	  }
	}
	
	var shownYet = 0;
	$('.show_all').click(function(){
		if(shownYet == 0){
			shownYet++;
			$('#country_select').show();
			$('#country_select').jScrollPane();
			$('#select_all_countries').find('.styledCheckbox').addClass('checked');
		} else {
			$('#country_select').show();
		}
	});
	
	$('#roaming_drop_down').mouseleave(function() {
		$('#country_select').slideUp(250);					
	});
	/* Setup select box */
	function createCountrySelect(){
		/* Propegate select dropdown with items */
		for(i=0; i<data.getNumberOfRows(); i++){
			$('#country_select').append('<div class="country" data-country-index="'+i+'"><input class="countrySelect" type="checkbox"></input><div class="countryListTitle">'+data.getValue(i, 0)+'</div></div>');
		/*now show the controls*/
		}
		$('input:checkbox.countrySelect').screwDefaultButtons({
		checked: 	"url(img/widget_checkbox_chkd.png)",
		unchecked:	"url(img/widget_checkbox.png)",
		width:		14,
		height:		14
	});
	showWidgetControls();
	function showWidgetControls(){
		$('.show_all').show();
		$('#results_button').show();
		$('#widget_msg').html('Choose one or more countries below');
	}	
		/* Select all countries click */
		$('#clear_checked').click(function(){
			if($('#select_all_countries').find(':checkbox').attr('checked', true)){
					$('#select_all_countries').find(':checkbox').attr('checked', false);
					$('#select_all_countries').removeClass('clicked');
			}
			
				$('#country_select').find(':checkbox').attr('checked', false);
				$('#country_select .country').removeClass('clicked');
				$('.styledCheckbox').css('background-image','url(img/widget_checkbox.png)');
				$('.styledCheckbox').removeClass('checked');
			countryIndex.length = 0;
			numCountries  = 0;
			$('#dropdown_msg').html(numCountries+' countries selected');
		});
		/* Select all countries click */
		$('#select_all_countries').click(function(){
			
			countryIndex.length = 0;
			numCountries = 0;
			//if($(this).find(':checkbox').attr('checked')){
			if($(this).find('.styledCheckbox').hasClass('checked')){
				$('#select_all_countries').find(':checkbox').attr('checked', false);
				$(this).find('.styledCheckbox').removeClass('checked');
				$(this).find('.styledCheckbox').css('background-image','url(img/widget_checkbox.png)');
				$(this).removeClass('clicked');				
				countryIndex.length = 0;
				numCountries = 0;
				$('#dropdown_msg').html('No countries selected');
			}else{
				$('#dropdown_msg').html('View pricing for all countries');
				$(this).find(':checkbox').attr('checked', true);
				$(this).find('.styledCheckbox').addClass('checked');
				$(this).find('.styledCheckbox').css('background-image','url(img/widget_checkbox_chkd.png)');
				$(this).addClass('clicked');
				if($('#country_select .country').hasClass('clicked')){
					$('.country').find(':checkbox').attr('checked', false);
					$('.country').removeClass('clicked');
					$('.country').find('.styledCheckbox').removeClass('checked');
					$('.country').find('.styledCheckbox').css('background-image','url(img/widget_checkbox.png)');
				}
			}
		});
		
		var selectAllCheckBox = $('#select_all_countries').find('.styledCheckbox');


		
		$(selectAllCheckBox).click(function(){
			
			countryIndex.length = 0;
			numCountries = 0;
			
			if($(this).hasClass('checked')){
				$(this).parent().find(':checkbox').attr('checked', false);
				$(this).parent().removeClass('clicked');
				$('#dropdown_msg').html('No countries selected');
				$(this).removeClass('checked');
				$(this).css('background-image','url(img/widget_checkbox.png)');
			}else{
				$('#dropdown_msg').html('View pricing for all countries');
				$(this).parent().find(':checkbox').attr('checked', true);
				$(this).parent().addClass('clicked');
				$(this).addClass('checked');
				$(this).css('background-image','url(img/widget_checkbox_chkd.png)');
				
				if($('#country_select .country').hasClass('clicked')){
					$('.country').find(':checkbox').attr('checked', false);
					$('.country').removeClass('clicked');
					$('.country').find('.styledCheckbox').removeClass('checked');
					$('.country').find('.styledCheckbox').css('background-image','url(img/widget_checkbox.png)');
				}
			}
			
		});
		
		/* Select country item click */
		$('.country').click(function(){
			$(this).toggleClass('clicked');
			var selectedIndex = $(this).data('country-index');
			if($('#select_all_countries').find(':checkbox').attr('checked', true)){
					$('#select_all_countries').find(':checkbox').attr('checked', false);
					$('#select_all_countries').toggleClass('clicked');
					$('#select_all_countries').find('.styledCheckbox').removeClass('checked');
					$('#select_all_countries').find('.styledCheckbox').css('background-image','url(img/widget_checkbox.png)');
					$(this).find('.styledCheckbox').addClass('checked');
					$(this).find('.styledCheckbox').css('background-image','url(img/widget_checkbox_chkd.png)');
					numCountries == 0;
			}
			/* If not in the index array - then add otherwise remove */
			if(jQuery.inArray(selectedIndex, countryIndex) === -1){
				countryIndex.push(selectedIndex);
				$(this).find(':checkbox').attr('checked', true);
				$(this).find('.styledCheckbox').addClass('checked');
				$(this).find('.styledCheckbox').css('background-image','url(img/widget_checkbox_chkd.png)');
				numCountries++;
				//(console).log(numCountries);
			}else{
				countryIndex.splice($.inArray(selectedIndex, countryIndex), 1 ); // Remove this clicked item from the array
				$(this).find(':checkbox').attr('checked', false);
				$(this).find('.styledCheckbox').removeClass('checked');
				$(this).find('.styledCheckbox').css('background-image','url(img/widget_checkbox.png)');
				numCountries--;
				//(console).log(numCountries);
			}
			/* Change the "drop-down" message */
			if (numCountries != 0){countryName = data.getFormattedValue(countryIndex[0], 0);}
			if (numCountries == 1){
				$('#dropdown_msg').html(countryName+' selected');
			} else if (numCountries == 0){
				$('#dropdown_msg').html(numCountries+' countries selected');
			} else if (numCountries > 1){
				$('#dropdown_msg').html(numCountries+' countries selected');
			}
		});
		$('#results_button').click(function(){
			var all = $('#select_all_countries').find(':checkbox').attr('checked');
			organiseData(all);
			if(all || countryIndex.length > 0){
				$('#results').show();
			}else{
				$('#results').hide();
			}
		});
	}//<!-- end create country function -->
	/* Loop through array of indexes and render results */
	function organiseData(showAll){
		$('#pricing_data').empty(); // remove previous dataset	
		if(showAll){		
			/* Loop through all selected items/countries */
			for(i=0; i<(data.getNumberOfRows()-1); i++){
			
				/* Loop through each row - getting column values - across ways */
				var row_data = {};
				for(j=0; j<data.getNumberOfColumns(); j++){
					var label = data.getColumnLabel(j).replace(/ /g,'');
					row_data[label] = data.getFormattedValue(i, j); // get formatted value
				}
				renderRow(i, row_data); // Render that guy out
			}
		}else{
			/* Loop through all selected items/countries */
			for(i=0; i<countryIndex.length; i++){
				/* Loop through each row - getting column values - across ways */
				var row_data = {};
				for(j=0; j<data.getNumberOfColumns(); j++){
					var label = data.getColumnLabel(j).replace(/ /g,'');
					row_data[label] = data.getFormattedValue(countryIndex[i], j); // get formatted value
				}
				renderRow(i, row_data); // Render that guy out
			}	
		} // end if show ALl
	}
	/* Render A row */
	function renderRow(id, rowData){
		var rowMarkup = '<div id="" class="CountryRoamingWrap"><div class="countryTitle">'+rowData.Destination+'</div>';
		rowMarkup += '<div class="roamPrice calling"><p class="the_price">'+rowData.Callswithincountry+'</p><p class="copyTC">Calls within '+rowData.Destination+'</p></div>';
		rowMarkup += '<div class="roamPrice calling"><p class="the_price">'+rowData.CalltoNZ+'</p><p class="copyTC">Call to NZ</p></div>';
		rowMarkup += '<div class="roamPrice calling"><p class="the_price">'+rowData.Callstoothercountries+'</p><p class="copyTC">Calls to other countries</p></div>';
		rowMarkup += '<div class="roamPrice other"><p class="the_price">'+rowData.DataPerMB+'</p><p class="copyTC">Data Per MB</p></div>';
		rowMarkup += '<div class="roamPrice other"><p class="the_price">'+rowData.Text+'</p><p class="copyTC">Text</p></div>';
		rowMarkup += '<div class="receiving">'+rowData.Receivingcalls+' to receive calls</div></div>';
	
		$('#pricing_data').append('<div id="'+id+'" class="CountryRoamingWrap">'+rowMarkup+'</div>'); // add markup
	}
	
	}//Roaming inti().
}//Roaming Ui/


/*storeUi*/

storeUi = {
	init : function () {
	
		var map;
		var zoom;
		var stores = {};
		var storeTypes = [];
		var mapOptions = {
		    zoom: 5,
		    center: new google.maps.LatLng(-41, 173),
		    mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		var infoWindow = new google.maps.InfoWindow();
		var markerCluster;
		var markerClusterOptions = {gridSize: 60, maxZoom: 13, zoom: parseFloat(zoom), styles: styles[0]};
		var markersArray = [];
		//var dataSourceUrl = 'http://spreadsheets.google.com/a/saltinteractive.com/tq?key=0Ao_ZAgp0FUwadG9WTkp5U2pUWWxOUVlEUU16MUVOdWc';
		var dataSourceUrl = 'https://docs.google.com/spreadsheet/pub?hl=en_GB&hl=en_GB&key=0Ao_ZAgp0FUwadG9WTkp5U2pUWWxOUVlEUU16MUVOdWc';
		var query;
		var searchBy;
		var option;
		var options;
		
		// Town/city change
		$('#select_city').change(function() {
			$('#select_suburb').empty();
			options = '<option>All Suburbs</option>';
			for (var suburb in stores[$(this).val()]) {
				options += '<option>'+suburb+'</option>';
			}
			$('#select_suburb').selectBox('options', options);
			options = '<option>All Stores</option>';
			if ($(this).val()=='All Towns/Cities') {
				for (i=0;i<storeTypes.length;i++) {
					options += '<option>'+storeTypes[i]+'</option>';
				}
			} else {
				for (var suburb in stores[$(this).val()]) {
					for (var store_type in stores[$(this).val()][suburb]) {
						if (options.search(store_type)==-1) {
							options += '<option>'+store_type+'</option>';
						}
					}
				}
			}
			$('#select_store').selectBox('options', options);
		});
		
		// Suburb change
		$('#select_suburb').change(function() {
			$('#select_store').empty();
			options = '<option>All Stores</option>';
			var selected_city = $('#select_city').val();
			if($(this).val()=='All Suburbs') {
				for (var suburb in stores[selected_city]) {
					for (var store_type in stores[selected_city][suburb]) {
						if (options.search(store_type)==-1) {
							options += '<option>'+store_type+'</option>';
						}
					}
				}
			} else {		
				for (var store_type in stores[$('#select_city').val()][$(this).val()]) {
					if (options.search(store_type)==-1) {
						options += '<option>'+store_type+'</option>';
					}
				}
			}
			$('#select_store').selectBox('options', options);
		});
		
		// Search button
		$('#show_btn').click(function(){
			searchStores();
			$('#store_results').show();
		});
		
		function clearOverlays() {
		  if (markersArray) {
		    for (i in markersArray) {
		      markersArray[i].setMap(null);
		    }
		  }
		}
		
		function createStores(data){
			clearOverlays();
			markersArray = [];
			for(i=0; i<(data.getNumberOfRows()); i++){
				var id = data.getFormattedValue(i,0);
				var name = data.getFormattedValue(i,1);
				var city = data.getFormattedValue(i,2);
				var suburb = data.getFormattedValue(i,3);
				var address = data.getFormattedValue(i,4);
				var contact_details = data.getFormattedValue(i,5);
				var notes = data.getFormattedValue(i,6);
				var has_sims = data.getFormattedValue(i,7);
				var has_handsets = data.getFormattedValue(i,8);
				var longitude = data.getFormattedValue(i,9);
				var latitude = data.getFormattedValue(i,10);
				var type = data.getFormattedValue(i,11);
	
				// create marker
				var latLng = new google.maps.LatLng( parseFloat(latitude) , parseFloat(longitude) );
				var marker = new google.maps.Marker({
					'position': latLng,
					'title': name,
					'address': address
				});
	
				google.maps.event.addListener(marker, 'click', function() {
					infoWindow.setContent('<div class="infoWindow"><h4><span class="copyStd">' + this.title + '</h4>' + this.address+'</span></div>');
		  			infoWindow.open(map,this);
				});
				markersArray.push(marker);
				
				// Add store to lookup object
				if (stores[city] == undefined) {
					stores[city] = {};
				}
				if (stores[city][suburb] == undefined) {
					stores[city][suburb] = {};
				}
				if (stores[city][suburb][type] == undefined) {
					stores[city][suburb][type] = {};
				}
				if ($.inArray(type,storeTypes)==-1) {
					storeTypes.push(type)
				}
				stores[city][suburb][type][name] = {
					"name": name,
					"address": address,
					"contact_details": contact_details,
					"has_handsets": 1,
					"notes": notes,
					"has_sims": has_sims,
					"longitude": longitude,
					"latitude": latitude
				}
			}
			
			// Init marker clusterer
			markerCluster = new MarkerClusterer(map, markersArray, markerClusterOptions);
			$('#loading_block').fadeOut(100);
			
			// Init towns/cities
			options = '<option>All Towns/Cities</option>';
			for (var town_city in stores) {
				options += '<option>'+town_city+'</option>';
			}
			$('#select_city').selectBox('options', options);
			
			// Init store types
			options = '<option>All Stores</option>';
			for (i=0;i<storeTypes.length;i++) {
				options += '<option>'+storeTypes[i]+'</option>';
			}
			$('#select_store').selectBox('options', options);
			// Ready to search
		}
		
		function createSidebarEntry(marker, name, address, type, latitude, longitude) {
			var div = document.createElement('li');
			var html = '<span class="stan-copy-strong">' + name + '</span> <span class="copyStd">' + address + '</span>';
			div.innerHTML = html;
			div.style.cursor = 'pointer';
			div.style.padding = '5px 5px 5px 0px'; 
			div.style.marginBottom = '3px'; 
			var latLng = new google.maps.LatLng(latitude, longitude);
			google.maps.event.addDomListener(div, 'click', function() {
				map.setCenter(latLng);
				map.setZoom(14);
				google.maps.event.trigger(marker, 'click');
			});
			return div;
		}
		
		function paginator(){
			$('#paginated_results').pajinate();
		}
		
		function searchStores() {
			clearOverlays();
			markersArray = [];
			bounds = new google.maps.LatLngBounds();
			
			var searchBy = 'Showing ';
			var town_city = $('#select_city').val();
			var suburb = $('#select_suburb').val();
			var store_type = $('#select_store').val();
			
			$('#paginated_results').html('<ul id="sidebar_result"></ul><div class="page_navigation"></div>');
			
			town_city = (town_city=='All Towns/Cities') ? false : town_city;
			suburb = (suburb=='All Suburbs') ? false : suburb;
			store_type = (store_type=='All Stores') ? false : store_type;
			
			if ((!store_type) && (!town_city)) {
				zoom = 5;
				searchBy +=" all stores in New Zealand";
				for (var town_city in stores) {
					for(var suburb in stores[town_city]) {
						for(var store_type in stores[town_city][suburb]) {
							for(var store in stores[town_city][suburb][store_type]) {
								createStore(stores[town_city][suburb][store_type][store]);
							}
						}
					}
				}
			} else if ((store_type) && (!town_city)){
				zoom = 5;
				searchBy += store_type+' stores across New Zealand';
				for (var town_city in stores) {
					for(var suburb in stores[town_city]) {
						for(var store in stores[town_city][suburb][store_type]) {
							createStore(stores[town_city][suburb][store_type][store]);
						}
					}
				}
			} else if (town_city && !store_type && !suburb) {
				zoom = 10;
				searchBy += ' all stores in '+town_city+', New Zealand';
				for(var suburb in stores[town_city]) {
					for(var store_type in stores[town_city][suburb]) {
						for(var store in stores[town_city][suburb][store_type]) {
							createStore(stores[town_city][suburb][store_type][store]);
						}
					}
				}
			} else if ((!store_type) && (suburb)) {
				zoom = 15;
				searchBy += ' all stores in '+suburb+', '+town_city +', New Zealand';
				for(var store_type in stores[town_city][suburb]) {
					for(var store in stores[town_city][suburb][store_type]) {
						createStore(stores[town_city][suburb][store_type][store]);
					}
				}
				
			} else if ((town_city) && (store_type) && (!suburb)) {
				zoom = 15;
				searchBy += store_type+' stores in '+town_city+', New Zealand';
				for(var suburb in stores[town_city]) {
					for(var store in stores[town_city][suburb][store_type]) {
						createStore(stores[town_city][suburb][store_type][store]);
					}
				}
			} else if ((suburb) && (store_type)) {
				zoom = 15;
				searchBy += store_type+' stores in '+suburb+', '+town_city +', New Zealand';
				for(var store in stores[town_city][suburb][store_type]) {
					createStore(stores[town_city][suburb][store_type][store]);
				}
			}
			$('#search_message').html(searchBy).show();
			$('#paginated_results').pajinate();
		}
		
		function createStore(rowData){
			var latLng = new google.maps.LatLng( parseFloat(rowData.latitude) , parseFloat(rowData.longitude) );
			var searchBy = 'Searching ';
			var marker = new google.maps.Marker({
				'position': latLng, 
				'title': rowData.name,
				'address': rowData.address
			});
			google.maps.event.addListener(marker, 'click', function() {
				infoWindow.setContent('<div class="infoWindow"><h4>' + this.title + '</h4><span class="copyStd">' + this.address+'</span></div>');
	  			infoWindow.open(map,this);
			});
			markersArray.push(marker);
			var sidebarEntry = createSidebarEntry(marker, rowData.name, rowData.address, rowData.type, rowData.latitude, rowData.longitude);
			$('#search_message').hide();
			$('#sidebar_result').append(sidebarEntry);
			bounds.extend(latLng);
			map.fitBounds(bounds);
			map.setCenter(bounds.getCenter());
			map.setZoom(zoom);
		}
	
		// Init map	
		map = new google.maps.Map(document.getElementById('map'), mapOptions);
		bounds = new google.maps.LatLngBounds();
	    query = new google.visualization.Query(dataSourceUrl);
		query.setQuery('select * order by C, D asc');
		query.send(function(response) {
			if (response.isError()) {
				alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
				return;
			} else {
				createStores(response.getDataTable());
			}
		});
	
	}//init():
}//store Ui/
