// JavaScript Document
function validate( formName, validations )
{
	clean = true;
	validation_list = $(validations).value.split(',');
	validation_list.each( function(id){ 
			var question = $(formName).elements[id];
			if (question)
			{
				if( question.value == 0  || question.value == '')
				{ 
					$(question).up('.entry').addClassName("error");
					clean = false;
				}
				else
				{
					$(question).up(".entry").removeClassName("error");
				}
			}
			else
			{
				alert(id);
			}
		});
	if (!clean) alert ("Please fill in the fields highlighted in Red");
	return clean;

}

/*
	Written by Jonathan Snook, http://www.snook.ca/jonathan
	Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function setDays( formObj, objName) {
	var y = formObj[objName+'year'].options[formObj[objName+'year'].selectedIndex].value;
	var m = formObj[objName+'month'].selectedIndex;
	var d;
	// find number of days in current month
	if ( (m == 3) || (m == 5) || (m == 8) || (m == 10) ) 
	{
		days = 30;
	}
	else if (m == 1) 
	{
		// check for leapyear - Any year divisible by 4, except those divisible by 100 (but NOT 400)
		if ( (Math.floor(y/4) == (y/4)) && ((Math.floor(y/100) != (y/100)) || (Math.floor(y/400) == (y/400))) )
			days = 29
		else
			days = 28
	}
	else 
	{
		days = 31;
	}
	
	// if (days in new month > current days) then we must add the extra days
	if (days > formObj[objName+'day'].length) 
	{
		for (i = formObj[objName+'day'].length; i < days; i++) 
		{
			formObj[objName+'day'].length = days;
			formObj[objName+'day'].options[i].text = i + 1;
			formObj[objName+'day'].options[i].value = i + 1;
		}
	}
	
	// if (days in new month < current days) then we must delete the extra days
	if (days < formObj[objName+'day'].length) 
	{
		formObj[objName+'day'].length = days;
		if (formObj[objName+'day'].selectedIndex == -1) 
			formObj[objName+'day'].selectedIndex = days - 1;
	}
}

function toggleMenu( menuElement )
{
	current_menu.className="";
	menuElement.className="picked";
	current_menu = menuElement;
	return true;	
}

function remove_item( update_area , object, id )
{
	if (confirm("Are you sure you want to remove this item?"))
	{
		new Ajax.Request(	domain+'/'+object+'/remove/'+id,
							{
								asynchronous:true, 
								evalScripts:true,
								onComplete: function(request){$('#'+update_area).slideUp();}
							}
						);
		return true;
	}
	return false;
}

function enable_item( update_area , object, id )
{
		new Ajax.Updater(	update_area, domain+'/'+object+'/enable/'+id+'&target_id=' +update_area,
							{
								asynchronous:true, 
								evalScripts:true,
								onComplete: function(request){$('#'+update_area);}
							}
						);
}

function remote_request(update_area, object, operation, id, form)
{
	form_parameters = "";
	if ($(form) && $(form).tagName=='FORM')
	{
		form_parameters = Form.serialize(form);
	}
	new Ajax.Updater(   update_area,
						domain+'/'+object+'/'+operation,
						{
							asynchronous:true, 
							evalScripts:true,
							onComplete: function(request){},	
							parameters: 'ajax=true&'+object+'[id]='+id+'&target_id='+update_area+"&"+form_parameters
						}
					);
}

var Helpers = {
	disclose: function (event) {	
		var update_area = event.target.id.split("disclose-")[1];
		var index = update_area.substr(update_area.lastIndexOf('-')+1);
		var object = update_area.substr(0,update_area.lastIndexOf('-'));
		var	operation = object.substr(object.lastIndexOf('-')+1);
		var object = object.substr(0,object.lastIndexOf('-'));
		var id = event.target.id;
		
		if ($(update_area).visible())
		{
			jQuery('#'+update_area).slideUp();	
			event.target.src = '/images/skins/default/disclose_right.gif';
		}
		else
		{
			event.target.src = '/images/spinning-wait-icons/wait20trans.gif';
			new Ajax.Updater(   update_area,
						domain+'/'+object+'/'+operation+"/"+index,
						{
							asynchronous:true, 
							evalScripts:true,
							onComplete: function(request){
								jQuery('#'+update_area).slideDown();
								$(id).src = '/images/skins/default/disclose_down.gif';
							},	
							parameters: 'ajax=true'
						}
					);
		}

	},
	
	man_disclose: function ( target )
	{
		target= $(target);
		var update_area = target.id.split("disclose-")[1];
		var items = update_area.split("-");
		var index = items[items.length-1];
		var object = items[0];//update_area.substr(0,update_area.lastIndexOf('-'));
		var	operation = items[1];//object.substr(object.lastIndexOf('-')+1);
		//var object = object.substr(0,object.lastIndexOf('-'));
		var id = target.id;
		
		if ($(update_area).visible())
		{
			//jQuery('#'+update_area).slideUp();	
			//target.src = '/images/skins/default/disclose_right.gif';
		}
		else
		{
			target.src = '/images/spinning-wait-icons/wait20trans.gif';
			new Ajax.Updater(   update_area,
						domain+'/'+object+'/'+operation+"/"+index,
						{
							asynchronous:true, 
							evalScripts:true,
							onComplete: function(request){
								jQuery('#'+update_area).slideDown();
								$(id).src = '/images/skins/default/disclose_down.gif';
							},	
							parameters: 'ajax=true'
						}
					);
		}
		
	},
	
	man_disclose_add: function ( target )
	{
		target= $(target);
		var update_area = target.id.split("disclose-")[1];
		var index = update_area.substr(update_area.lastIndexOf('-')+1);
		var object = update_area.substr(0,update_area.lastIndexOf('-'));
		var	operation = 'addEdit';
		var object = object.substr(0,object.lastIndexOf('-'));
		var id = target.id;
		
		if ($(update_area).visible())
		{
		//	jQuery('#'+update_area).slideUp();	
		//	target.src = '/images/skins/default/disclose_right.gif';
		}
		else
		{
			target.src = '/images/spinning-wait-icons/wait20trans.gif';
			new Ajax.Updater(   update_area,
						domain+'/'+object+'/'+operation+"/"+index,
						{
							asynchronous:true, 
							evalScripts:true,
							onComplete: function(request){
								jQuery('#'+update_area).slideDown();
								$(id).src = '/images/skins/default/disclose_down.gif';
							},	
							parameters: 'ajax=true'
						}
					);
		}
		
	},
	
	
	add: function (event) {
		var items = event.target.id.split("add-");
		update_area = items[1]+'add-'+items[2];
		var index = items[2];
		var object = items[1].substr(0,items[1].lastIndexOf("-"));
		var	operation = 'add';
		var id = event.target.id;
		
		new Ajax.Updater(   
			update_area,
				domain+'/'+object+'/'+operation+"/"+index,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){},	
					parameters: 'ajax=true',
					insertion: Insertion.Bottom
				}
		);
	},

	man_add: function (target) {
		target= $(target);
		var items = target.id.split("-");
		var index = items[items.length-1];
		update_area = items[1]+'-add-'+index;
		var object = items[1];
		var	operation = 'add';
		var id = target.id;
		
		new Ajax.Updater(   
				update_area,
				domain+'/'+object+'/'+operation+"/"+index,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){},	
					parameters: 'ajax=true',
					insertion: Insertion.Bottom
				}
		);
	},
	
	change: function (event) {
		var value = event.target.value;
		if (event.target.type=="checkbox" || event.target.type =='radio')
		{
			if (!event.target.checked)
				value= 0;
		}
		var id = event.target.id
		var index = id.substr(id.lastIndexOf("_")+1);
		var items = event.target.name.split("[");
		var object = items[0];
		var	operation = 'save_item';
		var column = items[1].substr(0,items[1].lastIndexOf("]"));
		
		new Ajax.Request(   
				domain+'/'+object+'/'+operation+'/'+index,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){},	
					parameters: 'ajax=true&'+object+'['+column+']='+value
				}
		);
	},
	
	man_remove: function(item)
	{
		var items = item.element.id.split('-');
		var index = items[items.length-1];
		var object = items[0];
		var	operation = 'remove';
		new Ajax.Request(   
				domain+'/'+object+'/'+operation+'/'+index,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){
						jQuery('#tr-'+object+'-'+index).slideUp();
					}	
				});
	},
	
	request: function (event) {
		var id = event.target.id
		var items = event.target.id.split("-");
		var object = items[1];
		var	operation = items[2];
		var index_start = String(items[1]).length+String(items[2]).length+2;
		var remaining = event.target.id.substr(index_start).replace('-','/');
		new Ajax.Updater('notifications',   
				domain+'/'+object+'/'+operation+''+remaining,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){
					},	
					parameters: 'ajax=true'
				}
		);
	}
		
}

function Ajax_alert()
{
	var box_position = $('body').cumulativeScrollOffset();
	var box_dims = $('ajax_flash_region').getDimensions();
	var screen_width = $('body').getWidth();
	box_position.top += 200;
	box_position.left += screen_width/2 - box_dims.width/2;
	$('ajax_flash_region').style.top = box_position.top+"px";
	$('ajax_flash_region').style.left = box_position.left+"px";
	new jQuery('#ajax_flash_region');
}

function edit_item( edit_area, object, id )
{
	new Ajax.Updater(	edit_area,
						domain+'/'+object+'/edit/'+id+'&target_id='+edit_area,
							{
								asynchronous:true, 
								evalScripts:true,
								onComplete: function (request){ alert("Add Highlighting Effect in HelperFunction.js") }
							}
						);
	return true;
}


function disable_items (item_list)
{
	items = item_list.split(",");
	if (items.length >0)
		items.each(function(item) { 
			if ($(item)){ 
				Element.hide(item); 

			}
		});
}

function enable_items (item_list)
{
	items = item_list.split(",");
	if (items.length >0)
		items.each(function(item) { 
			if ($(item)){ 
			Element.show(item);
			}
		});
}

function updating()
{
	return '<img src = "/images/spinning-wait-icons/wait30trans.gif">Please Wait!';
}

function getPageHeight() {
  var windowHeight
  if (self.innerHeight) {	// all except Explorer
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowHeight = document.body.clientHeight;
  }	
  return windowHeight
}

function getPageScroll() {
  var xScroll, yScroll;
  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
    xScroll = self.pageXOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
    yScroll = document.documentElement.scrollTop;
    xScroll = document.documentElement.scrollLeft;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
    xScroll = document.body.scrollLeft;	
  }
  return new Array(xScroll,yScroll) 
}

function show_notifications( content, mode ) {
	mode = mode || 'info';
	jQuery('#notifications').append(content).addClass( mode + ' ui-corner-all').css('top',getPageScroll()[1] + (getPageHeight() / 3)).css('left',(jQuery(window).width() - jQuery('#notifications').width() -20) / 2).show();
}

function hide_notifications( ) {
	jQuery('#notifications').html('').removeClass('info').removeClass('success').removeClass('warning').removeClass('error').hide();
}

function submitChange()
{
	jQuery.ajax({
		async: false,
		url: '/cart/update_cart',
		data: jQuery('select[name="products_selected[]"]').serialize()
	});
	
}

function searchVendorList(searchTerm, listLocal, callback)
{
	jQuery.ajax({
		async: true,
		url: '/vendor_training/searchCart',
		data: "search="+searchTerm,
		success: function (html) {
			jQuery(listLocal).parent('div').html(html);
			callback.call(this);
		}
	});
	return false;
	
}

function searchCourseList(searchTerm, listLocal, callback)
{
	jQuery.ajax({
		async: true,
		url: '/resources/searchCart',
		data: "search="+searchTerm,
		success: function (html) {
			jQuery(listLocal).parent('div').html(html);
			callback.call(this);
		}
	});
	return false;
	
}

function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		// You have to sign the code to enable this or allow the action in about:config by changing 
		//user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
}
