/*
* CHARITECH.COM
* Utility functions
* This file contains functions those need to perform small dynamic actions.
* 2009 - 02-09 
*/

$(document).ready( function () {
							 
	// Display Map
	renderMap();
	drawGraphs ();
	
	try {
		 $('#EntryStreet, #EntryCity, #EntryZip').bind('blur',findLocation);
		 $('#EntryState,#EntryCountry').bind('change',findLocation);
	} catch(e){};

	// add preview functionality
	$('.preview').click (previewVideo);
	imageTimer ();
	//filterData();
	initData();
	
});

// condition tab show/hide{
function showHideCondition( val) {
	
	if (val === true){
		$('#tab2').css({display:'block'});	
		$('#tab1').attr('width','136');
	}
	else {
		$('#tab2').css({display:'none'});
		$('#tab1').attr('width','100%');
	}
}

function previewVideo(e){
	// stop defalt event
	e.preventDefault();
	formatVideo ();
	 
	// find corrospnding teaxtarea
	parentTRTag = $(this).parents('tr');
	target = $(parentTRTag[0]).find('textarea');
	// add it to display box
	$('#hiddenModalContent').html($(target[0]).val());
	
	// get height and width
	objectTag = $('#hiddenModalContent > object');
	
	if (objectTag.length == 0)
		objectTag = $('#hiddenModalContent > embed');
	
	if (objectTag.length == 0){
		alert("Invalid codes!\nPlease add HTML object codes for video player.");
		return;
	}
	
	w_width = $(objectTag[0]).attr('width');
	w_height = $(objectTag[0]).attr('height');
	
	// view light box
	tb_show("Video Preview",'#TB_inline?height='+w_height+'&width='+w_width+'&inlineId=hiddenModalContent&modal=true',false);
	$('#hiddenModalContent').html('');
	/*
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	*/
	// add hidden functionality for light box
	setTimeout( function (){ $('#TB_ajaxContent').html($(target[0]).val())}, 100);
	
	$(document).bind('keydown',function(e){
		tb_remove();
		$(document).unbind('keydown');
	});
	return false;
}

function filterData (){
	// display loadiung bar
	$('#status').html('<img src="'+baseURL+'/images/loading.gif" />' );
	systemBusy = true;
	//post data to server
	 $.ajax({
	   type: "POST",
	   data :$("form").serialize(),
	   url: baseURL+"/search/",
	   dataType: "script",
	   success: function(msg){ systemBusy = false;   renderMap(); drawGraphs ();   },
	   error: function(msg){ systemBusy = false;  alert( "Sorry! Search failed. \nPlease try again."); $('#status').html(" Error occure while searching. Please try again." );  }
 	});
		
	return false;
}

function initData (){
	// display loadiung bar
	$('#status').html('<img src="'+baseURL+'/images/loading.gif" />' );
	systemBusy = true;
	//post data to server
	 $.ajax({
	   type: "POST",
	   data :$("form").serialize(),
	   url: baseURL+"/search",
	   dataType: "script",
	   success: function(msg){ systemBusy = false;  renderMap(); drawGraphs (); setTimeout(function () { $('#preview').css({display:'none'}); }, 3000);   },
	   error: function(msg){ systemBusy = false;  alert( "Sorry! Search failed. \nPlease try again."); $('#status').html(" Error occure while searching. Please try again." );  }
 	});
	
	
	return false;
}

/* Draw statisct charts */
function drawGraphs (){
	
	try {
	if (!graph)
		return;
	}catch (e){ return; }
		
	// display ET graph
	pct = 0;
	gt = '';
	gcolors ='';
	glabels = '';
	gdata = '';
							  
	colors = ['A9B4BA','EC7915','27DA42','D63B2A','1A91E7','B11AE7'];
	chapters = 0;
	names = ['','I had/have condition','Friend/Family has conditions','Professional Caregiver','I am scientist/research','I want to show my support'];
	for (j = 0; j < graph.entryTypes.length;j++){
		/*
		if (graph.entryTypes[j].id == 0){
			chapters++;
			continue;
		}
		*/
		gt += '<tr style="color:#'+colors[graph.entryTypes[j].id]+';"><td>'+(j+1)+'. '+names[graph.entryTypes[j].id]+"</td><td width='30' align='right' >"+graph.entryTypes[j].precentage+"%</td></tr>";	
		gdata += graph.entryTypes[j].precentage;
		gcolors += colors[graph.entryTypes[j].id];
		
		if (j+1 != graph.entryTypes.length){
			gdata += ',';
			gcolors += ',';
		}
	}
	gt = '<img width="190" src="http://chart.apis.google.com/chart?cht=p3&chs=190x100&chd=t:'+gdata+'&chco='+gcolors+'" /> <table width="100%" border="0" cellspacing="0" cellpadding="0">'+gt+"</table>";
	if (graph.entryTypes.length>0)
		$('#graph_et').html(gt);
	else
		$('#graph_et').html('<center>No results found.</center>');
	
	// display Location graph
	pct = 0;
	gt = '';
	gcolors ='';
	glabels = '';
	gdata = '';
	colors = ['FFBE22','86C984','0660DA','F578C4','FE9A66','A9B4BA'];
	for (j = 0; j < graph.locations.length;j++){
		
		if (graph.locations[j].name.length > 0) {
			gt += '<tr style="color:#'+colors[j]+';"><td>'+(j+1)+'. '+graph.locations[j].name+"</td><td width='30' align='right'>"+graph.locations[j].precentage+"%</td></tr>";
			pct += parseInt(graph.locations[j].precentage); 
			gdata += graph.locations[j].precentage;
			gcolors += colors[j];
			if (j+1 != graph.locations.length && graph.locations[j+1].name.length > 0 ){
				gdata += ',';
				gcolors += ',';
			}
		}
	}
	// add others value
	if (100- pct > 0){
		gt += '<tr style="color:#'+colors[5]+';"><td>'+(j+1)+'. Other</td><td width="30" align="right">'+(100-pct)+"%</td></tr>";
		gdata += ","+ (100-pct);
		gcolors += ","+colors[5];
	}
	gt = '<img width="190" src="http://chart.apis.google.com/chart?cht=p3&chs=190x100&chd=t:'+gdata+'&chco='+gcolors+'" /> <table width="100%" border="0" cellspacing="0" cellpadding="0">'+gt+"</table>";
	if (graph.locations.length>0)
		$('#graph_location').html(gt);
	else
		$('#graph_location').html('<center>No results found</center>');
		
	// display Conditions graph
	pct = 0;
	gt = '';
	gcolors ='';
	glabels = '';
	gdata = '';
	colors = ['349933','FE6C16','1A45A4','FE0034','AD0481','A4B6CA'];
	for (j = 0; j < graph.conditions.length;j++){
		gt += '<tr style="color:#'+colors[j]+';"><td>'+(j+1)+'. '+graph.conditions[j].name+"</td><td width='30' align='right'>"+graph.conditions[j].precentage+"%</td></tr>";
		pct += parseInt(graph.conditions[j].precentage); 
		gdata += graph.conditions[j].precentage+',';
		gcolors += colors[j]+',';
	}
	// add others value
	if (100-pct> 0){
		gt += '<tr style="color:#'+colors[5]+';"><td>'+(j+1)+'. Other</td><td width="30" align="right">'+(100-pct)+"%</td></tr>";
		gdata += (100-pct);
		gcolors += colors[5];
	}
	gt = '<img width="190" src="http://chart.apis.google.com/chart?cht=p3&chs=190x100&chd=t:'+gdata+'&chco='+gcolors+'" /> <table width="100%" border="0" cellspacing="0" cellpadding="0">'+gt+"</table>";
	if (graph.conditions.length)
		$('#graph_condition').html(gt);
	else
		$('#graph_condition').html("<center>No results found</center>");
}

/* Image slider functions */
var timeleft = 0;
var existing; 
function imageTimer (){
	
	if (!document.getElementById('imageSlider')){
		return;
	}
	
	//if (timeleft < 15)
	setTimeout(imageTimer,10000);
	rotateImages();
	timeleft++;
}

function rotateImages () {
	//alert('k');
	if (systemBusy)
		return;

	$.ajax({
	   type: "GET",
	   url: baseURL+"/entries/imageslider/r="+Math.random(),
	   dataType: "script",
	   success : function (data){
		  
		  try {
			  eval(data);
		  } catch (e) {}
		   // bulid list
		   stack = Array();
		   
		   $.each(randimages, function () {
				stack.push( '<div  class="imageItem"> <table border="0" cellspacing="0" cellpadding="2" width="100%"> <tr> <td align="center"><a href="'+baseURL+'/v/'+this.id+'"  ><img border="0" height="60" src="'+baseURL+'/thumb.php?i='+this.url+'"/></a></td> </tr>  <tr> <td align="center" height="20"><a href="'+baseURL+'/v/'+this.id+'">'+this.name+'</a></td> </tr> </table></div>');						
			});		   
		   
		 //  $('#imageSlider').html(text);
		   existing = $('#imageSlider div');
		   /*for (i = 0 ; i < 12; i++){
			   if (existing[i]) {
			   $(existing[i]).fadeOut(500, function () { $(this).remove(); });
			   }	
		   }*/
		  $(existing).fadeOut(500, function () { $(this).remove(); }); 
		   $('#imageSlider').append(stack.join(''));
		}
 	});
}

var x; 
function formatVideo (){
	
	//get all codes
	textAreas = $('#videocodes textarea');
	
	codePattern = /<object|<embed/i;
	urlPattern = /www.youtube.com/i;
	linkPattenrn = /<a/i;
	
	$.each(textAreas, function () {
		
		val = $.trim($(this).val());
		
		if (val.length == 0){
			return;	
		}

		if (codePattern.test(val)){
			// player code is there
			return;
		}
		
		if (urlPattern.test(val)){
			// link code is there, need to create object codes
			//http://www.youtube.com/watch?v=ZFm6aJuoS70
			tmp = val.split('=');
			if ( tmp.length > 1) {
				url = tmp[1];
				if ( tmp.length > 2) {
					tmp = url.split('&');
					url = tmp[0];
				}
				codes = '<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/'+url+'&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+url+'&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>';
			$(this).val(codes);
				return;
			}
		}
		
		//
		
		if (!linkPattenrn()) {
		// othrwise, create a link for given url
		$(this).val('<a href="'+val+'" target="_blank">'+val+'</a>');
		}
	});
}

