<?php require('../../../../wp-config.php'); ?>
<?php if(get_option('canvas_auto_publish') == 'true') $on_update = ', onUpdate:function(){ Canvas.saveAll;}';
		else $on_update = ', onUpdate: Canvas.changePublish'; ?>
Event.observe(window, 'load', function() { Canvas.initialize() }, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var CanvasAjax = Ajax;


var Canvas = {

	addListItem: function(id, name) {
		var count = $F('listcount');
		var elementId = id.parentNode;
		var copiedElement = elementId.cloneNode(true);
		copiedElement.id = name + count;
		copiedElement.firstChild.name = count + 'canvaslist_' + name;
		var parent = elementId.parentNode;
		parent.insertBefore(copiedElement, elementId.nextSibling);
		$('listcount').value++;
	},

	canvasOption: function(name, value) {
		var url = JS_CANVASURI + 'ajax/canvas-save-option.php';
		var pars = name+'='+value;
		var myAjax = new Ajax.Request(url, 
			{method: 'post', 
			parameters: pars }
			);
	},



	changePublishImg: function() {
		image = $('publish_image');
		if(image) image.src = JS_CANVASURI + 'images/publish-changed.gif';
	},
	
	changePublish: function(myelement) {
		
		Canvas.changePublishImg();
		Canvas.canvasHideMsg();
		
		if (myelement.id != "shelf"){
			default_template_name = $(myelement.id + '_' + 'template_name').value;
			template_size = Canvas.canvasMapTemplateSize($(myelement.id + '_' + 'template_size').value);
			allow_other_sizes = $(myelement.id + '_' + 'allow_other_sizes').value;
			allow_other_modules = $(myelement.id + '_' + 'allow_other_modules').value;
			default_module = $(myelement.id + '_' + 'default_module').value;
			
			var children = myelement.childElements();
			children.each( 
				function(myelement){
					if (myelement.hasClassName('container-plugin')){
						if (!(allow_other_modules) && default_module != $F(myelement.id + '_module_name')){
							myelement.remove();
							$('shelf').insert(myelement);
							Canvas.canvasDisplayMsg("Failed! Default module (" + default_module + ") only can be placed in this canvas.")
						}
						else if (Canvas.canvasMapTemplateSize($F(myelement.id + '_module_size')) > template_size){
							if (allow_other_sizes){
								Canvas.canvasDisplayMsg("Warning! You have placed a module with size greater than the canvas size.")
							}
							else{	
								myelement.remove();
								$('shelf').insert(myelement);
								Canvas.canvasDisplayMsg("Failed! The selected module size is greater than the canvas size.")
							}
						}
						if ($F(myelement.id + '_module_template_name') == "") $(myelement.id + '_module_template_name').value = default_template_name;
						if ($F(myelement.id + '_module_size') == "") $(myelement.id + '_module_size').value = template_size;

					}
			
			});		
		}
		else{
			// Make sure all template name and sizes for modules on the shelf are reset
			myelement.childElements().each( 
				function(childElement){
					if (childElement.hasClassName('container-plugin')){
						$(childElement.id + '_module_template_name').value = "";
						$(childElement.id + '_module_size').value = "";
						
					}
				}
			);
		}	
	},

	canvasDisplayMsg: function(msg) {
		
		$('canvas_status').style.display = "";
		$('canvas_status').innerHTML = "<p>" + msg +  "</p>";
	},

	canvasHideMsg: function(msg) {
		$('canvas_status').style.display = "none";
	},


	canvasMapTemplateSize: function(templateValue) {
		return templateValue;
		/*if (templateValue > 0) return templateValue;
		switch (templateValue){

			case "-1": // MODULE_TEMPLATE_SIZE_SMALL
				return 240;
				break;

			case "-2": // MODULE_TEMPLATE_SIZE_MEDIUM
				return 480;
				break;

			case "-3": // MODULE_TEMPLATE_SIZE_LARGE
				return 720;
				break;

			case "-4": // MODULE_TEMPLATE_SIZE_FULL
				return 960;
				break;
		}*/
		
	},

	endDrag: function(myelement) {
		//myelement.revert = true;
		//myelement.options.revert = true;
		
		
	},

	

	createDroppables: function(id) {
		var elements = $$('#'+id+' div.canvas_droppable_zone');
		var shelf = $('shelf');
		Sortable.create('shelf',{tag:'div', only: ['container','container-plugin'], overlap:'horizontal', handle:'handle', constraint:false, containment:elements.concat(shelf), dropOnEmpty:true<?php echo $on_update; ?>});

		elements.each(function(item){
			Sortable.create(item.id,{tag:'div', only: ['container','container-plugin'], overlap:'horizontal', handle:'handle', constraint:false, containment:elements.concat(shelf), dropOnEmpty:true<?php echo $on_update; ?>});
		
			//Grab default module
			default_module = $(item.id + '_' + 'default_module').value;
			allow_other_modules = $(item.id + '_' + 'allow_other_modules').value;

			default_template_name = $(item.id + '_' + 'template_name').value;
			template_size = Canvas.canvasMapTemplateSize($(item.id + '_' + 'template_size').value);
			
			var children = $('shelf').childElements();
			children.each( 
				function(myelement){
					if (default_module == $F(myelement.id + '_module_name')){
						// Check whether there is any modules in this canvas
						var children = $(item.id).childElements();
						modulesExist = false;
						children.each( function(item){
							if (item.hasClassName('container-plugin')){
								modulesExist = true;
							}
						});

						if (!modulesExist && LOAD_DEFAULT_MODULES){
							myelement.remove();
							$(item.id).insert(myelement);

							if ($F(myelement.id + '_module_template_name') == "") $(myelement.id + '_module_template_name').value = default_template_name;
							if ($F(myelement.id + '_module_size') == "") $(myelement.id + '_module_size').value = template_size;

							Canvas.changePublish($('shelf'));
							Canvas.canvasDisplayMsg("Default modules are added automatically to the canvas. Click Publish to save changes.");
							if (!(allow_other_modules)){
								myelement.select( 'h6.handle').find(function(s) {s.remove();});
							}
						}
					}
					
				}
			);
			
			var children1 = $(item.id).childElements();
			children1.each( 
				function(myelement){
					//console.log(item.id +" - " + myelement.id + '_module_name' +" - " +  Object.isElement(myelement.id + '_module_name') +" - " +  default_module+" - " ) ;
					if ($(myelement.id).hasClassName('container-plugin') && default_module == $F(myelement.id + '_module_name')){
						if (!(allow_other_modules)){
							myelement.select( 'h6.handle').find(function(s) {s.remove();});
						}
					}
					
				}
			);
		});
			

				
		/*Droppables.add('shelf', {
			accept: ['container','container-plugin']
		});

		var elements = $$('#'+id+' div.canvas_droppable_zone');
		elements.each(function(item){
			Droppables.add(item.id, {
					accept: ['container','container-plugin']
					});	
			
		});


		$$('#'+$F('canvas_page')+' div.canvas_droppable_zone').concat($('shelf')).each(function(item){
			var children = item.childElements();
			children.each( function(myelement){
						if (myelement.hasClassName('container-plugin')){
							new Draggable(myelement.id, {});
						}
			});	
		});*/
	},
	
	destroyDroppables: function(id) {
		Sortable.destroy('shelf');
		$$('#'+id+' div.canvas_droppable_zone').each(function(item){
			Sortable.destroy(item.id);
		});
	},
	

	gallerySwitch: function(id) {
		if($F('selected_image') != '') $($F('selected_image')).className = '';
		$(id).className = 'selected_image';
		$('selected_image').value = id;
		$('path').value = $F('directory')+id;
	},
	
	importXml: function() {
		var pars = 'path_to_xml='+$F('path_to_xml');
		$('export_message').className = "importing";
		var target = 'export_message';
		var url = JS_CANVASURI + 'ajax/canvas-import.php';
		var myAjax = new Ajax.Updater({success: target}, url, 
			{method: 'post', 
			parameters: pars,
			onComplete: function() { $('export_message').className = ''; $('export_message').style.paddingLeft = '0px'; }
			});
	},
	
	initialize: function() {
		//var bigdiv = document.createElement('div');
		//document.body.insertBefore(bigdiv, $('wphead'));
		//bigdiv.appendChild($('wphead'));
		//bigdiv.appendChild($('adminmenu'));
		//bigdiv.appendChild($('submenu'));
	
		var hide_instructions = $('hide_instructions');
		if(hide_instructions) {
			hide_instructions.onclick = function(){ 
				Canvas.canvasOption('canvas_show_instructions','0');
				new Effect.Fade('instructions', { duration: 0.4 });
				};
		}
		$$('ul.page_dropdown ul li a').each(function(item){
			//$(item).onclick = function(){ Canvas.switchCanvas(item.id) };
		});
		//$('show_content').onclick = function(){ Canvas.toggleMenu('show_content', 'hide_content', bigdiv); };
		//$('hide_content').onclick = function(){ Canvas.toggleMenu('show_content', 'hide_content', bigdiv); };
		$$('div.titlebar a img').each(function(item){
			$(item).onclick = function(){ Canvas.sortGroups(item.id) };
		});
		$$('.canvas_droppable_zone h8').each(function(item){
			$(item).onclick = function(){ Canvas.toggleZoneOptions(item.id) };
		});
		if($('canvas_page')) {
			mainpage = $F('canvas_page');
			curr_page = gup('t_page');
			if (curr_page == '')
				curr_page = mainpage;
			$(curr_page).style.display = "block";
			var mainmenu = $(curr_page+'__menu');
			if(mainmenu) { mainmenu.parentNode.className = 'selected'; }
			var publish = $('publish');
			if(publish) { publish.onclick = Canvas.saveAll; }
			Canvas.createDroppables(mainpage);
		}
	},
	
	removeListItem: function(id) {
		if(window.confirm('Are you sure you want to remove this item?')) {
			new Effect.Fade(id.parentNode,{ duration: 0.6, afterFinish: function(){ Element.remove(id.parentNode); } });
		}
	},

	restorePublish: function() {
		image = $('publish_image');
		if(image) image.src = JS_CANVASURI + 'images/publish.gif';
	},
	
	saveAll: function() {
		Canvas.canvasHideMsg();

		if($('publish')) { 
			$('publish').setStyle({backgroundImage: "url(" + JS_CANVASURI + "images/spinner.gif)"}); 
		}
		var layout_params;
		var saveCheckError = false;
		$$('#'+$F('canvas_page')+' div.canvas_droppable_zone').concat($('shelf')).each(function(item){

			if (item.id == 'shelf') {
				layout_params = Canvas.serializeHelper(layout_params, item.id);
				return; 
			}

			template_size = Canvas.canvasMapTemplateSize($(item.id + '_' + 'template_size').value);
			allow_other_sizes = $(item.id + '_' + 'allow_other_sizes').value;

			// Verify there are no invalid template size
			item.childElements().each(
				function(myelement){
					if (myelement.hasClassName('container-plugin')){
						if (Canvas.canvasMapTemplateSize($F(myelement.id + '_module_size')) > template_size){
							if (!allow_other_sizes){
								Canvas.canvasDisplayMsg("Error! You have placed module (" + $F(myelement.id + '_module_name') + ") with size greater than the canvas size.")
								saveCheckError = true;
							}
						}
							
					}
				});

			layout_params = Canvas.serializeHelper(layout_params, item.id);
		});

		if (!saveCheckError) {
			Canvas.saveLayout(layout_params);
			Canvas.zoneOptions();
		}
		else{
			if($('publish')){ $('publish').style.backgroundImage = "url('')"; Canvas.restorePublish(); }
		}
	},
	
	saveBlock: function(element, pars) {

		// Update the module template name and size
		$($F('updated_module_template_size_id')).value = $F('template_size'); //.getValue();
		$($F('updated_module_template_name_id')).value = $F('template_name');

		var url = JS_CANVASURI + 'ajax/canvas-save-plugin.php';
		var myAjax = new Ajax.Request(url, 
			{method: 'get', 
			parameters: pars }
			);
	},
	
	saveLayout: function(pars) {
		var url = JS_CANVASURI + 'ajax/canvas-save-layout.php';
		var myAjax = new Ajax.Request(url, 
			{method: 'get', 
			parameters: pars
			});
	},
		
	saveZone: function(pars) {
		var url = JS_CANVASURI + 'ajax/canvas-save-zone-options.php';
		var myAjax = new Ajax.Request(url, 
			{method: 'get', 
			parameters: pars,
			onComplete: function(){ if($('publish')){ $('publish').style.backgroundImage = "url('')"; Canvas.restorePublish(); } }
			});
	},

	serializeHelper: function(layout_params, block) {
		layout_params = Try.these (
			function() {
				  //template_name = Canvas.getBlockAttribute(block, 'template_name');
				  //template_size = Canvas.getBlockAttribute(block, 'template_size');	
	


				  content_exists = Canvas.customSerialize(block);//Sortable.serialize(block);

				  if (content_exists == '') {
					  return layout_params;
				  } else if (typeof(layout_params) == 'undefined')  {
					  return content_exists;
				  } else {
					  return layout_params + content_exists;
				  }
			}
		);
		return layout_params;
	},

	getBlockAttribute: function(block, attribute) {
		if (block != "shelf") { 
			attribute_val = $(block + '_' + attribute).value;
			return '_' + block + '_' + attribute + '=' + attribute_val + "&";
		}
		return "";
	},

	customSerialize: function(block) {
		newContent = Sortable.serialize(block) + "&";
	
		if (block != "shelf") { 
			name = encodeURIComponent(block);

			var children = $(block).childElements();
			children.each( 
				function(item){
					if (item.hasClassName('container-plugin')){
						newContent = newContent + "_" + name + "_template_size[]=" + encodeURIComponent($F(item.id + '_module_size')) + "&";
						newContent = newContent + "_" + name + "_template_name[]=" + encodeURIComponent($F(item.id + '_module_template_name')) + "&";
				}
			});
		}

		return newContent;
	},





	
	sortGroups: function(group) {
		if(group == 'all') {
			$$('div.shelf_column div').each(function(item){
				$(item).style.display = 'block';
			});
		} else {
			$$('div.shelf_column div.container').each(function(item){
				$(item).style.display = 'none';
			});
			$$('div.shelf_column div.container-plugin').each(function(item){
				$(item).style.display = 'none';
			});
			$$('div.shelf_column div.'+group).each(function(item){
				$(item).style.display = 'block';
			});
		}
	},
	
	switchCanvas: function(element) {
		var currentPage = $F('canvas_page');
		$$('ul.page_dropdown ul li').each(function(item){ if($(item).className == 'selected') $(item).className = ''; });
		$(element).parentNode.className = 'selected';
		var string = element.split('__');
		$(currentPage).style.display = 'none';
		Canvas.destroyDroppables(currentPage);
		$(string[0]).style.display = 'block';
		$('canvas_page').value = string[0];
		Canvas.createDroppables(string[0]);
	},
	
	toggleMenu: function(show,hide,block) {
		if($(block).style.display == "none") {
			$(show).style.display  = "none";
			$(hide).style.display = "inline";
			new Effect.BlindDown(block, {duration: 0.3 })
		} else {
			$(show).style.display  = "inline";
			$(hide).style.display = "none";
			new Effect.BlindUp(block, {duration: 0.3 })
		}
	},
	
	toggleZoneOptions: function(id) {
		if($(id.replace('togglezoneoption_','options_')).style.display == 'block') {
			$(id.replace('togglezoneoption_','options_')).style.display = 'none';
			$(id).style.backgroundColor = '#CFCFCF';
		} else {
			$(id.replace('togglezoneoption_','options_')).style.display = 'block';
			$(id).style.backgroundColor = 'transparent';
		}
	},
	
	zoneHandler: function(zone, position) {
		$$('span#options_' + zone + ' img').each(function(item){
			item.src = item.src.replace('_down', '_up');
			item.src = item.src.replace(position+'_up', position+'_down');
		});
		$('zoneoption_'+zone).value = position;
		Canvas.changePublish();
	},

	zoneOptions: function() {
		string = '';
		$$('#'+$F('canvas_page')+' select.zone_content_options').each(function(item){
			string = string + '&' + item.id + '=' + $F(item.id);
		});
		Canvas.saveZone(string);
	}
};


// This code was found here: http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Francis Cocharrua :: http://scripts.franciscocharrua.com/ */

function Select_Value_Set(SelectName, Value) {
	eval('SelectObject = document.' + SelectName + ';');

	for(index = 0; index < SelectObject.length; index++) {
		if(SelectObject[index].value == Value)
			SelectObject.selectedIndex = index;
	}
}

/*
	Get the value of an HTML GET parameter
*/
function gup( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}