// JavaScript Document
//var heightEff = new Fx.Morph('container',{duration: 500, transition: Fx.Transitions.Quad.easeInOut}).start({'height': fullSize});
var timerID = 0;

/**
  * update the url form field based on the content of another thing (usualy the title etc)
**/
function updateURLField(field, string, table, parent, id) {
	
	var temp = new String(string);
	temp = stripVowelAccent(string);
	temp = temp.replace("'",'');
	temp = temp.replace(/[^a-zA-Z0-9]+/g,'-');
	
	var val = temp.toLowerCase();
	
	// ajax request to check for current item
	if(!parent) {
		parent = '0';
	}
	
	document.getElementById(field).value = temp.toLowerCase();

	clearTimeout(timerID);
	timerID = setTimeout('checkUrl(\''+table+'\', \''+val+'\', \''+parent+'\', \''+id+'\')', 1500);
		
}


/**
  * gets rid of unwanted accented characters in a string
**/
function stripVowelAccent(str) {
	var s = str;
	
	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
	/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
	/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
	/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
	/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];
	
	var repChar=['A','a','E','e','I','i','O','o','U','u'];
	
	for(var i=0; i<rExps.length; i++) {
		s=s.replace(rExps[i],repChar[i]);
	}
	
	return s;
}


/**
  * check the url name via ajax call
  * return html / string to output to form
**/
function checkUrl(table, val, parent, id) {
	
	var req = new Request({method: 'get', 
						  	autoCancel: true,
						  	url: '/ajax_gateway/checkUrlname.php',
							onSuccess: function(response){
					
								$('urlOk').innerHTML = response;

							}
							}
						  );
	
	req.send('t='+table+'&u='+val+'&p='+parent+'&id='+id);
}


/**
  * holds all info and functions for the timed ajax edit_lock table update
  * php defined global (JAVA_EDIT_TIMER - /defaults/javadefaults.php) holds the reference to the initial call
  * edit manager class sets up data and starts the regular ajax calls 
**/
function setUpdateTimer() {
	
	var userID = null;
	var module_name = null;
	var itemID = null;
	
	var intID = null;
	
	this.setUpdateDetails = function(u, m, i) {
		userID = u;
		module_name = m;
		itemID = i;
	}
	
	this.set = function(time) {
		t = (!time) ? 60000 : time;
		intID = setInterval(updateEditInfo, t, this.userID, this.module_name, this.itemID);
	}
	
	function updateEditInfo() {
		var req = new Request({method: 'get', url: '/ajax_gateway/updateEditInfo.php'});
		req.send('u='+userID+'&m='+module_name+'&i='+itemID);
		
	}
	
}


/**
  * bulk add view restrictions to pages
  * this function is recursive and checks / unchecks all children from a certain level until no more children are found
  * @el: object; the initial checkbox item that is checked
**/
function permissionsTickChildren(el) {
	var val = el.checked;
	var children = $('el_'+el.value).getChildren();
	
	for(var i = 0; i<children.length; i++) {
		children[i].getFirst().checked = val;
		
		if(document.getElementById('el_'+children[i].getFirst().value)) {
			permissionsTickChildren(children[i].getFirst());
		}
	}
}


/**
  * shows or hides the date field for setting an items display dates
  * also affects the notifications date field - simply for the user interface
**/
function showHideDate(val) {
	var disp  = (val) ? "block" : "none";
	var nDisp = (val) ? "none" : "block";
	
	var elements = $$('p.showHide');
	for(var i = 0; i<elements.length; i++) {
		//elements[i].style.display = disp;
		elements[i].setStyle('display', disp);
	}
	
	$$('span#notificationDateField').setStyle('display', nDisp);
}





function setSliders(item, control, content) {

	var sliders = new Array();
	
	var items = document.getElements(item);
	
	for(var i = 0; i<items.length; i++) {
	
		var sliderContent = items[i].getElement(content);
		var sliderControl = items[i].getElement(control);
		
		sliders[i] = new Fx.Slide(sliderContent);
		sliders[i].show();

		sliderControl.i = i;
		sliderControl.addEvent('click', function() {
											sliders[this.i].toggle(); 
										} );
	}
	
}

function parseTickProducts(){
	console.log('running');
	$$('div.tick h4').addEvent('click',function(){
										console.log(this.name);
										tickboxes(this.getParent('div').getChildren('input[type=checkbox]'), this.getParent('div').getFirst('input[type=checkbox]'));
										});
}

function tickboxes(el,el2){
console.log( $$(el) );
console.log( $(el2) );

if ( $(el2).checked ) {
		$$(el).set('checked',false);
	}
	else {
		$$(el).set('checked');
	}	


}

function pollVote() { 
	
	var p = $('pollform');
	if(p){			  
	p.addEvent('submit' , function() { 
				p.set('send', {url: '/ajax_gateway/ajaxGateway.php',
							method: 'get',
							onSuccess: function(response){
								pollResults(response);
							}
							});

				p.send(); //Sends the form.
				return false;
				} );
	}
	
}

function pollResults(resp){
	var res = JSON.decode(resp);
	var vts = JSON.decode(res.results);
	//console.log(res);
	
	var keys = new Array('A', 'B', 'C', 'D', 'E', 'F');
	
	switch(res.status){
	
	case 'okay':
		alert('Your vote has been logged, thank you');
		//replace poll with graph
		$$('div#poll input').setStyles({display: 'none'});
		i = 0;
		$each(vts, function(value, key){
			if(res.showValues == 1) {
    			$('pa_'+key).set('text',' ('+value+ '%)');
    			$('l_'+key).set('text',keys[i]);
				i++;
    		}
		});
		
		var gchrt = g_Chart(vts, res.type);
		$('cht').set('html', gchrt );
		//increase div height
		el = $('poll').getParent('div').getParent('div');
		nh = el.getStyle('height').toInt();
		el.setStyle('height', nh + 130);

		break;
	case 'duplicate':
		alert('You have already voted in this poll');
		break;
	case 'error':
		alert('Sorry there was a problem logging your vote');
		break;
	}
}

function g_Chart(res, type){
	var width = 230;
	var height = 130;
	var type = (type) ? type : 'p';
	var colors = '29B713,919B98,8DC2A6,67CC57,BDC9AC';
	var labA = Array();
	var datA = Array();
	var i = 0;
	var l = 'ABCDEFGHIJKLMNOP';
	//reorder the results
	$each(res, function(value, key){
		//console.log(value+'>'+key);
		labA[i] = l.substr(i,1);
		datA[i] = value;
		i++;
		});
	var ch_args = Array();
	ch_args[0] = 'chs='+width+'x'+height;
	ch_args[1] = 'cht='+type;
	ch_args[2] = 'chd=t:'+datA.join(',');
	ch_args[3] = 'chl='+labA.join('|');
	ch_args[4] = 'chco='+colors;
	g_url = 'http://chart.apis.google.com/chart?'+ch_args.join('&');	
	g_html = '<img src="'+g_url+'" width="'+width+'" height="'+height+'" />';
	//console.log(g_html);
	return g_html;

}

function ratingStars() { 

	var stars = $$('div.star-rating li a');
	var req = new Request({method: 'get', 
						  	autoCancel: true,
						  	url: '/ajax_gateway/ajaxGateway.php',
							onSuccess: function(response){
								setRated(response);
							}
						  });
	stars.addEvent('mouseover' , function() { 
		
		t = parseInt( this.getParent('li').id.substr(2,1) );
		for(i=1;i<t;i++){
			$('s_'+i).getChildren('a').set('class', 'hover');
		}
		} );
				
	stars.addEvent('mouseout' , function() { 
		$$('div.star-rating li a').set('class', '');

		} );				
					
								  
	stars.addEvent('click' , function() { 
				
				li = argToGet(this.href);
				req.send('mode=rating'+li);
				return false;
				} );
	
}

function argToGet(url){
	li = url.substr( url.indexOf('/q/') ).replace(/-/g, "=");
	sp = li.replace(/\//g, "&");
	return sp;
}


function setRated(resp){
	//resp is a json object

	var res = JSON.decode(resp);
	switch(res.status){
	
	case 'okay':
		alert('Your rating has been logged, thank you');
				
		for(var i=1;i<6 ; i++){
			if(i<=Math.floor(res.newAve) ){
				$('s_'+i).set('class', 'rated');
			}else{
				$('s_'+i).set('class', 'unrated');
			}
		}
		
		$('aveVotes').innerHTML = res.newAve;	
		$('numVotes').innerHTML = res.newCount;
		
		break;
	case 'duplicate':
		alert('You have already rated this article');
		break;
	case 'error':
		alert('Sorry there was a problem logging your rating');
		break;
	}
	
}