/*
 *	Javascript functions for JCDecaux Premiere Profiler. Built with love by David Tait 2008
 *	Requires jQuery.js - built on version 1.3 - and jQuery.scrollTo.js
 *
 */

function catcher(err){
	alert("error - " + err + " (this is WIP!)")
}

// checks the from age isn't higher than the to age, and if it is, changes the other select box
function checkage(tofrom){
	var curfrom = $('#agefrom').selectedValues();
	var curto = $('#ageto').selectedValues();
	if(curfrom[0] > curto[0]){
		if(tofrom == 'from'){
			var s = parseInt(curfrom[0])+9;
			$('#ageto').selectOptions(s.toString());
		}else{
			var s = parseInt(curto[0])-9;
			$('#agefrom').selectOptions(s.toString());
		}	
	}
	sitesearch();
}

// gathers the age ranges we want to search with
function gatherages(){
	// get whats selected
	var from = parseInt($('#agefrom').attr('value'));
	var to = parseInt($('#ageto').attr('value'));
	// the figures to loop thru
	var vals = [15,25,35,45,55,65];
	var tmp = [];
	for(i in vals){
		if(vals[i] >= from){ // if the val is bigger than the selected from
			if((vals[i]+9) <= to){ // and 9 bigger than the val isnt higher than the selected to
				var f = (vals[i] == 15) ? 16 : vals[i]; // fix 15 to 16
				var t = ((vals[i]+9) == 74) ? 'Plus' : 'to'+(vals[i]+9); // fix 74 to Plus
				tmp.push(f + t); // push into array
			}
		}
	}
	var rtn = tmp.join("_") // same as phps implode
	return rtn;
}

// was the original search function but just warns the user to update results
function sitesearch(){
	$('#updatealert').slideDown('fast');
}

// the main search function, gathers search requests and does the ajax thang
function sitesearcher(){
	// gather the variables
	var a = ''; // age
	var s = ''; // sex
	var g = ''; // grade
	var l = ''; // limit
	var f = ''; // format
 	var c = ''; // city
	var p = ''; // postcode
	var d = ''; // distance
	var tc =''; // textsearch
	var px =''; // personicx
	
	// AUDIENCE
	if($('#audiencecontent').length != 0){
	if(ison('#audiencecontent')){
		if(ison('#agegendergradefieldset')){
			a = gatherages();
			s = $('#sex').attr('value');
			g = $('#grade').attr('value');
			g = (g=="All") ? '' : g;
			if(a == '16to24_25to34_35to44_45to54_55to64_65Plus' && s == 'All' & g == ''){
				alert('Invalid audience selection - you need to change at least one of the "Age, Gender & Grade" options');
				exit;
			}
		} else {
			gatherpersonicx()
			if(window.selectedpersonicx.length == 0){
				alert('Invalid Personicx selection - you must select at least one Personicx');
				exit;
			}
			if(window.selectedpersonicx.length == 60){
				alert('Invalid Personicx selection - you cannot select all personicx');
				exit;
			}
			px = window.selectedpersonicx.join('+');
		}
		l = $('#limit').attr('value'); 
		l = (l=="No") ? '' : l;
	}
	}

	
	// LOCATION
	if(ison('#locationcontent')){ 
		if($('#locationcontent #postcode').css('display')=="none"){
			var c = $('#cities').attr('value'); 
		}else{
			if($('#postcodesearch').attr('value') != undefined){
				var p = $('#postcodesearch').attr('value');
				var d = $('#radius').attr('value');
			} else {
				alert('please enter a postcode');
				exit;
			}
		}
	}
	// FORMAT
	var f = (ison('#formatcontent')) ? gatherformats() : '';
	// TEXT SEARCH
	if(ison('#textsearchcontent')){
		tc = $('#textsearch').attr('value');
		if(tc==undefined) {
			alert('please enter some text to search for'); 
			exit;
		}
	}
	// we've survived, so lets do search, so show loading stuff
	$('#hiddenwarning').hide()
	$('#toolbar').show()
	loading()
	// the ajax bit - concentrate
	$.get("includes/php/sitesearch.php", { formats: f, cities: c, textsearch: tc, postcode: p, distance: d, age: a, sex: s, grade: g, limit: l, personicx: px },
		function(data){ // after we've got the returned data
			// split the data up (would be better to use json but not on decaux server)!
			var data = data.split("|");
			// update the siteList	
			document.getElementById('siteList').innerHTML = data[0];
			//alert(sites)
			// updatemap
			var mapids = data[1]; 
			updatemap(mapids);
			window.allmapids = mapids
			
			// display the result count
			var s = $(".site").length
			if(s==0){
				document.getElementById('rightresults').innerHTML = "</b>No sites found matching your filters</b>";
				window.map.drawZoomAndCenter(window.uk,12);
			}else{
				document.getElementById('rightresults').innerHTML = "Showing <b>" + $(".site").length + "</b> sites matching your filters. Click the site names for more details.";
			}
			// turns the last orange marker to blue again
			switchlastmarker()
			// show the listandmap
			$('#listandmap').css('display','block');
			// turn off the searching button
			$('#searchbut').removeClass('selected');
			// and change the text back
			$('#searchbuttext').empty().append('Search');
			// slide up the update warning
			$('#updatealert').slideUp('fast');

			$('#siteList').scrollTo( 0, 1000 );
			
			$('#profiler').css('visibility','visible');
			
			$('#preload').hide();
			
		}); 
}

function updatemap(mapids){
		//hide all markers 
		for(i in window.markerids){ window.markers[window.markerids[i]].hide();};
		// go thru map ids turning them on
		var geos = new Array();
		var mapids = mapids.split(',');
		for(i in mapids){
			if(window.markers[mapids[i]]){
				window.markers[mapids[i]].unhide();
				geos.push(window.markers[mapids[i]].YGeoPoint);
			}
		};
		var center = window.map.getBestZoomAndCenter(geos);     
		var newpoint = new YGeoPoint(center.YGeoPoint.Lat,center.YGeoPoint.Lon);
		window.map.drawZoomAndCenter(newpoint, center.zoomLevel);
}

// checks if a filter is on or off by checking its display value. used by sitesearcher
function ison(target){
	if($(target).css('display')!="none") return true;
	else return false;
}

previouscode = "12345678912346598";
function checkpostcode(){
	var code = $('#postcodesearch').attr('value');
	if(previouscode != code){
		if(code == "" || code == undefined){ 
			$('#postcodesearchresult').empty().append("Please enter a postcode"); 
		}else{
			var postcode = code.split(" ").join("")
			$('#postcodesearchresult').html('Searching...');
			$.getScript("includes/php/checkpostcode.php?postcode=" + postcode);
		}
	}
	previouscode = code;
}

function gatherformats(){
	var f="";
	var bs = $(".formatcheckbox").not(".checkboxunselected").children('b');
	for(i=0;i<bs.length;i++){
		f += bs[i].innerHTML + "-";
	}
	if(f=="") f = "none";
	return f;
}

function loading(){
	$('#listandmap').css('display','none');
	$('#rightresults').empty().append("Searching");
}

function hideunselected(){
	$('#selectioncontrolhidden').show()
	$('.selectioncontrol').hide()
	$('.sitecheckbox').not(".sitecheckboxselected").parent('div').parent('div').hide()
	updatemap(gatherselectedids())
}

function gatherselectedids(){
	var ids = [];
	$('.sitecheckboxselected').parent().parent().each(function(i){
		ids.push(this.id);
	});
	return ids.join(",");
}

function exportexcel(){
	var ids = new Array();
	$('.sitecheckboxselected').parent().parent().each(function(i){
		var distance = $('#' + this.id + ' #distance').text();
		var audience = $('#' + this.id + ' #audience').text();
		audience.replace(' ','+');
		ids.push(this.id + "|" + distance + "|" + audience);
	});
	var rtn = ids.join("/")
	if(ids.length == 0) {
		alert("No Sites have been selected (Ticked)");
		exit;
	}
	window.open('includes/php/exportexcel.php?ids='+rtn,'_self')
}

function averageaudience(){
	$('#averageaudience').load("includes/php/averageaudience.php",{ids:gatherselectedids()})
}

function showall(){
	$('.selectioncontrol').show()
	$('#selectioncontrolhidden').hide()
	$('.site').show();
	$('#siteList input').attr('disabled',false);
	updatemap(window.allmapids)
}

function countsites(){
	var divs = $('#siteList').$(".site").length;
	return divs;
}

function sitechecktoggle(target){
	target.toggleClass("sitecheckboxselected");
	if($("#selectioncontrolhidden").css("display") != "none") { 
		target.parent("div").parent('div').slideUp("fast") 
	}
}

function personicxchecktoggle(target){
	target.toggleClass("personicxcheckboxselected");
	countpersonicx()
}

function personicxfiltertoggle(target,classname){
	if(target.is('.checkboxunselected')) {
		$('.px'+classname).css('display','')
	}else{
		$('.px'+classname).css('display','none')
	}
	target.toggleClass('checkboxunselected');
	countpersonicx()
}

window.selectedpersonicx = new Array()
function gatherpersonicx(){
	// make empty arrat
	var pers = new Array();
	var selected = $('.personicxcheckboxselected');
	// for each selected
	$.each( selected, function(i){
	  //push the parents id (its personicx code) into array	
		var parent = selected.eq(i).parent('div')
		if(parent.css('display') != 'none' && parent.parent('div').css('display') != 'none'){
	  		pers.push(parent.parent().attr('id'));
		}
	});
	// the main array is the daddy!
	window.selectedpersonicx = pers;
}
function countpersonicx(){
	var count = 0;
	// for each selected
	var selected = $('.personicxcheckboxselected');
	$.each( selected, function(i){
	  //push the parents id (its personicx code) into array	
		var parent = selected.eq(i).parent('div')
		if(parent.css('display') != 'none' && parent.parent('div').css('display') != 'none'){
	  		count++;
		}
	});
	count = (count==0) ? 'No' : count; // if no set to "no"
	// print result
	$('#personicxcount').children('span').text(count);
	$('#personicxcountleft').children('span').text(count);
}

function showpersonicxdesc(target){
	if(!target.parent().siblings('.desc').is('.descopen')){
		$('.descopen').slideUp('fast').removeClass('descopen'); 
		target.parent().siblings('.desc').slideToggle('fast').addClass('descopen');
		var t = target.parent();
		$('personicxlist').scrollTo(200,1000);
	} else {
		target.parent().siblings('.desc').slideToggle('fast').removeClass('descopen');	
	}
}

function formatchecktoggle(target){
	target.toggleClass('checkboxunselected');
	sitesearch();
}

function locationchecktoggle(){
	$('.locationcheckbox').toggleClass('radiounselected');
	$('#city').slideToggle('fast');
	$('#postcode').slideToggle('fast');
	sitesearch();
}

function audiencechecktoggle(){
	$('.audiencecheckbox').toggleClass('radiounselected');
	$('#personicxfieldset').slideToggle('fast');
	$('#agegendergradefieldset').slideToggle('fast');
	sitesearch();
}

function siteswitchphoto(photo){
	$('#photoimg').html('<img alt="' + photo + '" src="includes/php/thumbnail.php?img=../../assets/photos/large/'+ photo + '.jpg&w=450&h=300" width="450px" height="300px" />');
}

function downloadphoto(){
	var p = $('#photoimg img').attr('alt');
	p = 'includes/php/downloadphoto.php?code=' + p;
	window.open(p,'_self');
}

function showonmap(target){
	try{
		// turn previous ones off
		switchlastmarker()
		// move the map to the new location
		window.map.drawZoomAndCenter(new YGeoPoint(window.markers[target].YGeoPoint.Lat,window.markers[target].YGeoPoint.Lon),3);
		window.markers[target].changeImage(new YImage('assets/ui/markerorange.png',new YSize(12,20)));	
		div = $("#"+target + " .sitemapmark")
		div.addClass("showing").parent('div').parent('div').addClass('siteselected');
		window.lastdiv = div;
		window.lastmarker = target;
	} catch(err) {
		catcher(err)
	}
}

function showinlist(target){
	$("#siteList").scrollTo('#'+target,1000);
	switchlastmarker()
	// move the map to the new location
	window.markers[target].changeImage(new YImage('assets/ui/markerorange.png',new YSize(12,20)));	
	div = $("#"+target + " .sitemapmark")
	div.addClass("showing").parent('div').parent('div').addClass('siteselected');
	window.lastdiv = div;
	window.lastmarker = target;
}

function switchlastmarker(){
	if(window.lastmarker) {
		window.markers[lastmarker].changeImage(new YImage('assets/ui/markerblue.png',new YSize(12,20)));
		window.lastdiv.removeClass('showing').parent('div').parent('div').removeClass('siteselected');
		window.lastmarker = false;
		window.lastdiv = false;
	}
}   


