/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}


/**
 * Function used to write a filename to a form's input field
 *
 * Has a JQUERY dependency now
 *
 * @param object OBJ The submitted JS form object w/ the filename values
 * @param string formname The id of the form to write to
 * @param string idname The id of the field to write to (necessary only for non-tinymce forms
 *
 */
function fillform(obj,formname,idname) {
	var imageFile = null;
	if (!formname) {
		formname = 'imageform';
	}
	/*
 	for (var i = 0; i< obj.filename.length; i++) {
 		if (obj.filename[i].checked) {
 			imageFile = obj.filename[i].value;
 		}
 	}*/
 	
 	imageFile = $("input:checked").val();
 	
 	if (imageFile) {
 	//window.opener.product.photo.value = filename;
 	if (formname == 'linkform') {
 		window.opener.document.getElementById(eval("formname")).href.value = imageFile;
 	} else if (formname=='imageform') {
  		window.opener.document.getElementById(eval("formname")).src.value = imageFile;
  	} else {
  		window.opener.document.getElementById(eval("idname")).value = imageFile;  
  	}
 self.close();
 }
}


function clearText(formName,inputfield,writeDivID) {
     document.getElementById(eval(formName)).eval(writeDivID).innerHtml = filterNum(document.getElementById(eval(formName)).eval(inputfield).value);

     function filterNum(str) {
          re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\ |\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
          // remove special characters like "$" and "," etc...
          return str.replace(re, "");
     }
}


function dateDiff(initialNumber)
	{
		if (!initialNumber) {
			initialNumber = 1;
		}
		var duration = null;
		var fields = '';
		
		if (document.getElementById("EventDuration").value) {
			duration = document.getElementById("EventDuration").value;
			if (!isNaN(duration)) {
				if (duration < 10) {
					//first hide them all
					for (i=1;i<=10;i++) {
						if (document.getElementById("perfTimes"+i)) {
							document.getElementById("perfTimes"+i).style.display = 'none';
						}
					}
					for (i=1;i<=duration;i++) {
						if (document.getElementById("perfTimes"+i)) {
							document.getElementById("perfTimes"+i).style.display = 'block';
						}
					}
				}
			
			}
		} 

		if (fields) {
			document.getElementById("datedifference").innerHTML = fields;
		}
	
	
	
	}

// Author: Eric King Url: http://redrival.com/eak/index.shtml
// This script is free to use as long as this info is left in
// Courtesy of SimplytheBest.net - http://simplythebest.net/scripts/

function NewWindow(mypage,myname,w,h,scroll){
	var win = null;
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
	win = window.open(mypage,myname,settings)
}

/**
 * Function to pull in the images and file lists for add content pages
 * Loads in a URL into a specified divName, and applies the function to
 * all the links inside the loaded page (to preserve the ajaxed-ness
 */
function loadPiece(href,divName,model) {	
	$(divName).load(href, {}, function(){
		makeItemChecked(model);

		var divChildren = divName+" a";
		$(divChildren).not('.thickbox').click(function() { 	
			var thisHref = $(this).attr("href");
			loadPiece(thisHref,divName,model);
			return false;
		});
	});
}

function toggleItemExistence(id,name,model,currentAttachmentLocation)
{
	if ($("#"+model+"-item-"+id).val()>=0) {
		removeItemFromList(id,model);
		removeItemFromList(id,model,currentAttachmentLocation);
	} else {
		addItemToList(id,name,model);
	}
	
	return false;

}

function removeItemFromList(id,model,ItemLocation)
{
	if (ItemLocation== undefined) {
		ItemLocation = model;
	}
	$("#"+ItemLocation+'-table tr.element-id-'+id).remove();
	/* This may have been executed through a link, and not
		by unchecking the checkbox, so make sure the checkbox
		gets unchecked
	*/
	$("#"+model+id).attr("checked","");
	updateCurrentListSize(model);
	
	/* Update the Table Drag-n-drop */
	$("#"+ItemLocation+'-table').tableDnD({
	    onDragClass: "itemDragClass",
	    onDrop: function(table, row) {
        	 reOrderItems(model);
	    }
	});
	reOrderItems(model);
}



/**
 * Callback function for post-ajax item list load in admin-add/edit page
 * It looks to see if a model's data is listed, and if they are, check the id's
 * for the listed content in the ajax list window for consistency
 */
function makeItemChecked(model)
{
	var numberOfItems = countSidebarListItems(model);
	if (numberOfItems > 0 ) {
		
		$("input[@id^="+model+"-item-]").each(function(i) {
			var id = this.value;
			//window.alert(id);
			$("#"+model+id).attr("checked","checked");
		});
	
	}
	
	return true;

	

}

/**
 * Count the number of Items in a sidebar list
 * @param string Model The name of the model that will have a list
 * @return integer The number of items for that model
 */
function countSidebarListItems(model)
{
	var count = $("input[@id^="+model+"-item-]").size();
	if (isNaN(count)) {
		count = 0;
	}
	return count;
}


/**
 * Adds a hidden input element to the sidebar, listed in a pre-defined div
 * area by model name.  These elements are in the proper cake format for a 
 * HABTM relationship when the data is saved in the controller.
 *
 * @param integer Id The id of the item in question
 * @param string Name The name to display in the queue
 * @param string Model The model name of the data to work with
 * @return null But writes table rows to a specified Table div by model name
 */
 
function addItemToList(id,name,model) {
	var currentNumberofItems = countSidebarListItems(model);
	newEntryNumber = currentNumberofItems + 1;
	var toWrite = '';
	toWrite = '<tr id="'+newEntryNumber+'" class="element-id-'+id+'"><td>';
	toWrite += '<label for="'+model+'-item-'+id+'">'+name+'</label>';
	toWrite += '<input type="hidden" name="data['+model+']['+model+'][]" value="'+id+'" id="'+model+'-item-'+id+'" />'+"\n";
	toWrite += '</td><td>';
	toWrite += '<a href="#" class="remove" onclick="removeItemFromList(\''+id+'\',\''+model+'\');return false;">&nbsp;</a>';
	toWrite += '</td></tr>';
	
	$("#"+model+"-list table").append(toWrite);
	
	//initialize table
	$("#"+model+"-table").tableDnD({onDragClass: "itemDragClass",onDrop: function(table, row) {
            var rows = table.tBodies[0].rows;
           // var debugStr = "Row dropped was "+row.id+". New order: ";
            reOrderItems(model);
	    }
	    
	});

	displaySaveButton(model);
	
}

function reOrderItems(model)
{
	var count = countSidebarListItems(model);
	var counter = 0;
	if (count > 0) {
		$("input[@id^="+model+"-item-]").each(function (i) {
			$(this).attr("name","data["+model+"]["+model+"]["+counter+"]");
			counter = counter + 1;
		});
	}
	return true;
}

/**
 * Display the save button on update ordering
 */
function displaySaveButton(model)
{
	var displayed = $(".orderingButtonSave"+model).css("display");
	if (displayed == 'none') {
		$(".orderingButtonSave"+model).css({display:"block"});
	}
}

/**
 * Checks to see if the browser is IE 6 or less.  If it is, show a warning screen.
 */
function browserCheck()
{
	var browser = jQuery.browser;
	if(browser.msie == true) {
		if (browser.version < 7.0) {
			window.alert('You are using an unsupported version of Internet Explorer ('+browser.version+').  WebTree requires Internet Explorer 7.0 or above. Please upgrade to the latest version by going to http://www.microsoft.com/ie.  If you continue, many features of WebTree will be inoperable and the interface will not display properly.');
		}
	}
}

/**
 * Updates the number of attached items in a specified span tag
 * used for counting the attached elements in the admin sidebar
 */
function updateCurrentListSize(model)
{
	
	var count = $("input[@id^="+model+"-item-]").filter('.current').size();
	if (isNaN(count)) {
		count = 0;
	}
	if ($("#currentNumber-"+model).text() != undefined) {
		$("#currentNumber-"+model).text(count);
	}


}

function GeneratePassword() {
  
    var length=8;
    var sPassword = "";
    
    var noPunction = true;
    
    for (i=0; i < length; i++) {
    
        numI = getRandomNum();
        if (noPunction) { while (checkPunc(numI)) { numI = getRandomNum(); } }
        
        sPassword = sPassword + String.fromCharCode(numI);
    }
    
    return sPassword;
}



function getRandomNum() {
        
    // between 0 - 1
    var rndNum = Math.random()

    // rndNum from 0 - 1000    
    rndNum = parseInt(rndNum * 1000);

    // rndNum from 33 - 127        
    rndNum = (rndNum % 94) + 33;
            
    return rndNum;
}

function checkPunc(num) {
    
    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }    
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }
    
    return false;
}

function writeRandomPassword(inputClass)
{
	$(inputClass).val(GeneratePassword());
	// trigger note
	if ($("#passwordWarning").text() == "") {
		$(inputClass).after('<p id="passwordWarning" class="quiet note">You may want to write this password down, once you save it, you cannot see it again.</p>');
	}


}