function debug(log_txt) {
    if (window.console != undefined) {
        console.log(log_txt);
    }
}

function updateOrder()
{
	//alert(Sortable.serialize('tbody_list'));
	var options = {
		method : 'post',
		postBody : 'section='+section+'&'+Sortable.serialize('items')
	};

	//location.href='_lib/cms/_ajax/update_order.php?'+options['postBody'];
	new Ajax.Request('_lib/cms/_ajax/update_order.php', options);
}

function showProgress(on){
	if(on){
		var dialog = jQuery("#dialog");
		if (jQuery("#dialog").length == 0){
			dialog = jQuery('<div id="dialog" title="Loading">Please wait..</div>').appendTo('body');
		}
		
		jQuery( "#dialog" ).dialog({
			closeOnEscape: false,
			open: function(event, ui) { jQuery(this).parent().children().children('.ui-dialog-titlebar-close').hide(); },
			height: 140,
			modal: true
		});
	}else{
		jQuery( "#dialog" ).dialog("close");
	}
}

function initForms()
{
	jQuery('form.validate').bind('submit', function(evt) {
		evt.preventDefault();
		
		showProgress(true);
		
		//disable buttons
		jQuery('*[type=submit], *[type=image]',this).attr('disabled', '');;
	
		//remove error messages
		jQuery('div.error').remove();
		
		//validate
		jQuery.ajax( location.href, {
			dataType: 'json',
			type: 'post',
			data: this.serialize()+'&validate=1',
			success: jQuery.proxy(function(returned){        
				options = jQuery(this).attr('validateoptions');
				
				if(!options){
					options=[];
				}
				
				if( options.errorMethod==undefined ){
					options.errorMethod='inline'
				}
				
				debug(returned);
			
				if( parseInt(returned)!=returned-0 ){
					if( returned.length>0 ){
						
						//display errors
						var errors='';
						
						for( i=0;i<returned.length;i++ ){
							var pos=returned[i].indexOf(' ');
							
							if( pos==-1 ){
								var field=returned[i];
								var error='Required';
							}else{
								var field=returned[i].substring(0,pos);
								var error=returned[i].substring(pos+1);
							}
							
							var parent='';
							
							if( this[field] ){
								if( this[field].style ){
									if( !firstError ){
										var firstError=field;
									}
									
									parent=this[field].parentNode;
								}else if( this[field][0] ){
									parent=this[field][0].parentNode.parentNode;
								}
								errors+=field+'\n';
							}else if( this[field+'[]'] ){
								if( this[field+'[]'].style ){
									if( !firstError ){
										var firstError=field;
									}
									
									parent=this[field+'[]'].parentNode;
								}else if( this[field+'[]'][0] ){										
									parent=this[field+'[]'][0].parentNode.parentNode;
								}
								
								errors+=field+'\n';
							}else{
								errors+=error+'\n';
							}
													
							if( parent && options.errorMethod=='inline' ){
								div = document.createElement("div");
								div.innerHTML=error;
								div.style.color='red';
								div.className='error';
								
								parent.appendChild(div);
							}
						}
						
						if( options.errorMethod=='alert' ){
							alert('Please check the required fields\n'+errors);
						}
						
						//show first error
						var tab, node;
						
						node=this[firstError];
						
						while( node=node.parentNode ){					
							if( node.style.display=='none' ){
								tab=node.id;
								break;
							}
							
							if( node.nodeName=='BODY' ){
								break;
							}
						}
						
						if( tab && set_tab ){
							debug('switch tab: '+tab);
							
							set_tab(tab);					
						}
						
						//focus field
						this[firstError].focus();
					}
					
					//remove error messages
					jQuery('*[type=submit], *[type=image]',this).removeAttr('disabled');
					
					showProgress(false);
				}else{
					//submit form					
					window.onbeforeunload = null;
					
					this.submit();
				}
			},this)
		});

		//show progress  
	});
}

function initAutoGrows()
{
	jQuery('textarea.autogrow').bind('keyup', function() {
		this.style.overflow = "hidden";
		this.style.fontSize = 12 + "px";
		//var textarea = _gel("stickyText12");
		var cols = this.cols;
		var str = this.value;
		str = str.replace(/\r\n?/, "\n");
		var lines = 2;
		var chars = 0;
		for (i = 0; i < str.length; i++) {
			var c = str.charAt(i);
			chars++;
			if (c == "\n" || chars == cols) {
				lines ++;
				chars = 0;
			}
		}
		
		if( this.rows>lines ){
			lines=this.rows;	
		}
		
		this.style.height = lines*14 + "px";	
	});
		
	jQuery('textarea.autogrow').trigger('keyup');
}

function initComboBoxes()
{
	if( jQuery('select.combobox').length ){
		jQuery("head").append("<link>");
		var css = jQuery("head").children(":last");
		css.attr({
			rel:  "stylesheet",
			type: "text/css",
			href: "/_lib/js/jquery.ui.combobox/jquery.ui.combobox.css"
		});
		
		jQuery.getScript("/_lib/js/jquery.ui.combobox/jquery.ui.combobox.js").done(function(){
			jQuery('select.combobox').combobox();
		});
	}
}

function initDateFields()
{
	jQuery('input.date').datepicker({
		dateFormat: 'dd/mm/yy',
		altFormat: 'dd/mm/yy'
	});
}

function initTimeFields()
{
	if( jQuery('input.time').length ){
		jQuery("head").append("<link>");
		var css = jQuery("head").children(":last");
		css.attr({
			rel:  "stylesheet",
			type: "text/css",
			href: "/_lib/js/jquery.ui.timepicker/jquery.ui.timepicker.css"
		});
		
		jQuery.getScript("/_lib/js/jquery.ui.timepicker/jquery.ui.timepicker.js").done(function(){
			jQuery('input.time').timepicker();
		});
	}
}

var maps={};
function initMaps()
{
	var inputs=jQuery('input.map');
	
	if( inputs.length==0 ){
		return;
	}
	
	google.load("maps", "3", {other_params: "sensor=false", "callback" : function(){
		jQuery.each(jQuery('input.map'), function() {		
			div = document.createElement("div");
			div.style.width='600px';
			div.style.height='400px';
			
			this.parentNode.appendChild(div);
			
			var coords=null;
			
			if( this.value ){
				coords = this.value.split(',');
			}else{
				coords=[51.8100844,-0.02911359999995966];
			}
			
			var lat=coords[0];
			var lng=coords[1];
			
			var latlng = new google.maps.LatLng(lat, lng);
			var myOptions = {
				zoom: 10,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			maps[this.name] = new google.maps.Map(div, myOptions);
			
			maps[this.name].markers=[];
			maps[this.name].markers.push(new google.maps.Marker({
				map: maps[this.name],
				position: latlng,
				draggable:true
			}));

			google.maps.event.addListener(maps[this.name].markers[0], "dragend", function() {
				var latlng=this.getPosition();
				this.value=latlng.lat()+','+latlng.lng();
			});	
		});
	}});
}

function initRatingFields()
{
	if( jQuery('select.rating').length ){
		jQuery("head").append("<link>");
		var css = jQuery("head").children(":last");
		css.attr({
			rel:  "stylesheet",
			type: "text/css",
			href: "/_lib/js/jquery.ui.stars/jquery.ui.stars.css"
		});
		
		jQuery.getScript("/_lib/js/jquery.ui.stars/jquery.ui.stars.js").done(function(){
			jQuery('select.rating').parent().stars({
				inputType: "select"
			});
		});
	}
}

var _editor_lang = "en";
var _editor_url = "_lib/js/xinha-0.96.1/";

var xinha_init = function(){
	var xinha_editors=[];
	
	var i=1;
	jQuery('textarea.xinha').each(function() {			
		this.id='xinha'+i;				
		xinha_editors.push(this.id);
		
		i++;
	});
	
	var xinha_plugins =  [
		'Phpupload',
		'PasteText',
		'Linker',
		'Stylist',
		'TableOperations',
		'InsertAnchor'
	];

	// THIS BIT OF JAVASCRIPT LOADS THE PLUGINS, NO TOUCHING  :)
	if(!Xinha.loadPlugins(xinha_plugins, xinha_init)) return;

	var xinha_config = new Xinha.Config();
	
	xinha_config.toolbar = [
		["popupeditor"],
		[ "formatblock", "space",
		  "bold", "italic", "underline" ],
				
		[ "justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
		  "insertorderedlist", "insertunorderedlist","outdent","indent", "separator",
		  "forecolor", "hilitecolor", "separator",
		  'inserthorizontalrule', "createlink", 'insertimage', "killword", "htmlmode"
		   ]
	];
	
	xinha_config.stripBaseHref=false;			
	xinha_config.stripScripts=false;			
	xinha_config.killWordOnPaste=true; //not supported by FF
	
	/*
	if( custom_css ){
		xinha_config.stylistLoadStylesheet('/css/cms.css');
	}*/

	xinha_editors = Xinha.makeEditors(xinha_editors, xinha_config, xinha_plugins);
	Xinha.startEditors(xinha_editors);
}

function initXinhas()
{
	if( jQuery('textarea.xinha').length ){
		jQuery.getScript("/_lib/js/xinha-0.96.1/XinhaCore.js").done(xinha_init);
	}
}

function numbersonly(e){
	var unicode=e.charCode? e.charCode : e.keyCode
	
	if (unicode!=8 && unicode!=46 && unicode!=9){ //if the key isn't the backspace key or dot or tab (which we should allow)
		if (unicode<48||unicode>57){ //if not a number
			return false //disable key press
		}
	}
}

function addItem(aList,aField) {	
	phpUploadCallback=function(images){
		for( i in images ){
			if( images.hasOwnProperty(i) ){			
				rows++;
			
				var ul = document.getElementById(aList);
				li = document.createElement("li");
				li.setAttribute('id', 'item-' + rows);
				
				var itemHTML='<input type="hidden" id="image'+rows+'" name="'+aField+'[]" value="'+images[i]+'" size="5"> ';
				itemHTML+='<img src="_lib/phpupload/?func=preview&file='+images[i]+'" id="image'+rows+'_thumb" width="100" height="100" /><br /> ';
				itemHTML+='<label id="image'+rows+'_label">'+images[i]+'</label><br />';
				//itemHTML+='<span class="link" onClick="phpUpload(\'image'+rows+'\')">Choose</span> ';
				itemHTML+='<a href="javascript:void(0)" class="link" onClick="delItem(\'item-'+rows+'\')">Delete</a>';
				
				li.innerHTML=itemHTML;
				
				ul.appendChild(li); 
				
				Sortable.create(aField+'_files');
			}
		}		
	};
	
	phpUpload();
}

function delItem(aItem,aField) {
	rows--;
	
    var obj = document.getElementById(aItem);
    obj.parentNode.removeChild(obj);
	
	Sortable.create(aField+'_files');
}

function addFile(aList,aField) {
	rows++;

	var ul = document.getElementById(aList);
	li = document.createElement("li");
	li.setAttribute('id', 'item-' + rows);
	
	var itemHTML='<input type="file" name="'+aField+'[]" /> ';
	itemHTML+='<a href="javascript:;" onClick="delFile(\'item-'+rows+'\')">Delete</a>';
	
	li.innerHTML=itemHTML;
	
	ul.appendChild(li); 
	
	Sortable.create(aField+'_files');
}

function delFile(aItem,aField) {
	rows--;
	
    var obj = document.getElementById(aItem);
    obj.parentNode.removeChild(obj);
	
	Sortable.create(aField+'_files');
}

function clearFile(field)
{
	var inputHidden = document.getElementById(field);
	inputFile = document.createElement("input");
	inputFile.setAttribute('name', field);
	inputFile.setAttribute('type', 'file');
	
	var cell=inputHidden.parentNode;
	
    while ( cell.childNodes.length >= 1 )
    {
        cell.removeChild( cell.firstChild );       
    } 
	
	cell.appendChild(inputFile);
}

function clearItem(aField) {
    var field = document.getElementById(aField);
	var thumb = document.getElementById(aField+'_thumb');
	var label = document.getElementById(aField+'_label');

	field.value='';
	thumb.src='_lib/phpupload/?func=preview&file=';
	label.innerHTML='';
}

function selectAll(field){
	jQuery('input').each(function() {	
		if( this.name==field+'[]' ){
			this.checked=true;
		}
	});
}

function selectNone(field){
	jQuery('input').each(function() {	
		if( this.name==field+'[]' ){
			this.checked=false;
		}
	});
}

function addRowrelated(aTable) {
	rows++;

	aRow = aTable.insertRow(aTable.rows.length);

	aCell = aRow.insertCell(0);
	aCell.innerHTML= '<select name="related[]" id="related'+rows+'"></select>';
	
	aCell = aRow.insertCell(1);
	aCell.innerHTML= '<a href="javascript:;" onClick="delRow(this)">Delete</a>';
}

function delRow(row) {
	rows--;
	row.parentNode.parentNode.parentNode.deleteRow(row.parentNode.parentNode.rowIndex);
}

var phpUploadCallback;

function phpUpload(field)
{
	var file;
	
	if( field ){
		file=document.getElementById(field).value;
	}
	
	window.open('_lib/phpupload/?field='+field+'&file='+file,'Insert','width=700,height=450,screenX=100,screenY=100,left=100,top=100,status,dependent,alwaysRaised,resizable,scrollbars')
}

function init_tabs()
{
	var tabs=$$('.tab');
	
	tabs.each(function(name, index) {
		if( index==0 ){
			set_tab(name.target);
		}
					   
		name.observe('mousedown', function(e){ set_tab(e.target.target) });
	});
}

function set_tab(target)
{
	var tabs=$$('.tab');
	
	tabs.each(function(name, index) {
		if( target==name.target ){
			$(name.target).style.display='block';
			name.addClassName('current')
		}else{
			$(name.target).style.display='none';
			name.removeClassName('current')
		}
	});
}

jQuery(document).ready(function() {
	initForms();
	initDateFields();
	initTimeFields();
	initMaps();
	initRatingFields();	
	initComboBoxes();
	initXinhas();
});
