function getVal(id) {
	return document.getElementById(id).value;
}

function ucwords (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
 
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}

function set_src(id, val) {
	document.getElementById(id).src = val;
}

function setChk(id) {
	document.getElementById(id).checked = true;
}

function unsetChk(id) {
	document.getElementById(id).checked = false;
}

function getHTML(id) {
	return document.getElementById(id).innerHTML;
}

function submitFormDialog(id) {
	var content = getHTML("dialog_"+id);
	
	if (confirm(content)) {
		document.getElementById("f_"+id).submit();
	}
}

function submitForm(id) {
	document.getElementById(id).submit();
}

function setVal(id, val) {
	document.getElementById(id).value = val;		
}

function getHTML(id) {
	return document.getElementById(id).innerHTML;
}

function submitDialog(id) {
	if (confirm(getHTML("msg_"+id)) ) {
		document.getElementById("f_"+id).submit();
	}
}

function showDiv(id) {
	document.getElementById(id).style.display = "block";
}

function set_focus(id) {
	document.getElementById(id).focus();
}

function get_checked(id) {
	return document.getElementById(id).checked;
}

function hideDiv(id) {
	document.getElementById(id).style.display = "none";
}

function set_class(id, nclass) {
	document.getElementById(id).className= nclass;
}

function redirect(path) {
	window.location = "<?=$mainAppPath?>"+path;
}

function checkEmpty(array) {
	var x;
	for (x in array) {
		if (getVal(array[x]) == "") {
			showDiv("div_" + array[x]);
		}
	}
	
	for (x in array) {
		if (getVal(array[x]) == "") {
			set_focus(array[x]);

			return false;
		}
	}
	return true;
}

function checkEmptyNew(str) {
	var x;
	var y;
	var array = str.split(",");
	var tmp = "";
	
	for (x = 0; x < array.length; x++) {
		tmp = trim(getVal(array[x]));
		if ( tmp == "") {
			showDiv("div_" + array[x]);
		} else {
			hideDiv("div_" + array[x]);		
		}
	}
	
	for (x = 0; x < array.length; x++) {
		if (trim(getVal(array[x])) == "") {
			set_focus(array[x]);
			return false;
		}
	}
	
	return true;
}

function checkEmailValidator(id) {
	var email = getVal(id);
	
	isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
	if(email!='' && String(email).search(isEmail_re) == -1) {
		showDiv("div_"+id);
		return false;
	}
	
	hideDiv("div_"+id);	
	return true;
}

function checkNumaricNew(str) {
	var x;
	var array = str.split(",");
	
	for (x = 0; x < array.length; x++) {
		if ( isNaN(getVal(array[x])) ) {
			showDiv("div_" + array[x]);
		} else {
			hideDiv("div_" + array[x]);		
		}
	}
	
	for (x = 0; x < array.length; x++) {
		if ( isNaN(getVal(array[x])) ) {
			set_focus(array[x]);
			return false;
		}
	}
	return true;
}

function updateVal(id, val) {
	setVal(id, val);
}

function showErrorMsg(title, msg) {
	alert(msg);
}


function setHTML(id, val) {
	document.getElementById(id).innerHTML = val;
}

function setXHTML(id, val) {
	document.getElementById(id).innerHTML = val;
}

function updateValue(id1, id2) {
	setVal(id2, getVal(id1));
}

function showFlickerImagesMain() {
	var val = getVal("search");
	showFlickerImageLocal(val);
}

function add_to_wishlist(book_id, user_id) {
	if(user_id==''){
		window.parent.location = "index.php?req=login";
		return;
	}
	
	url = "ajaxAddToWishlist.php";
	getVars = "action=add_to_wishlist"+"&book_id="+book_id+"&user_id="+user_id;
	
	loading_image_id = 'loading_'+book_id;
	
	$(loading_image_id).show();
	
	new Ajax.Request(
					 	url, 
						{
							parameters:getVars,
							asynchronous:false,
							onLoading:function() {},
							onComplete: function(transport) {
								$('remove_from_wishlist_'+book_id).show();
								$('add_to_wishlist_'+book_id).hide();
								$(loading_image_id).hide();
								response_text = transport.responseText;
							}
						}
					);
}

function remove_from_wishlist(book_id, user_id) {
	if(user_id==''){
		window.parent.location = "index.php?req=login";
		return;
	}
	
	url = "ajaxAddToWishlist.php";
	getVars = "action=remove_from_wishlist"+"&book_id="+book_id+"&user_id="+user_id;
	
	loading_image_id = 'loading_'+book_id;
	
	$(loading_image_id).show();
	
	new Ajax.Request(
					 	url, 
						{
							parameters:getVars,
							asynchronous:false,
							onLoading:function() {},
							onComplete: function(transport) {
								$('add_to_wishlist_'+book_id).show();
								$('remove_from_wishlist_'+book_id).hide();
								$(loading_image_id).hide();
								response_text = transport.responseText;
							}
						}
					);
}

function delete_comment(comment_id) {
	url = "ajaxAddToWishlist.php";
	getVars = "action=delete_comment"+"&comment_id="+comment_id;
	
	hide_div_id = 'comment_'+comment_id;
	
	new Ajax.Request(
					 	url, 
						{
							parameters:getVars,
							asynchronous:false,
							onLoading:function() {},
							onComplete: function(transport) {
								$(hide_div_id).hide();
								response_text = transport.responseText;
							}
						}
					);
}


//XML Object For AJAX Call
function GetXmlHttpObject() {
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		//Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function addBr(id) {
	var val = getVal(id);
	var tmp = "";
	val = val.split(" ");
	var climit = 25;
	for (var x = 0; x < val.length; x++) {
		if (val[x].length > climit) {
			val[x] = tokenize(val[x], climit);
		}
	}
	
	for (x = 0; x < val.length; x++) {
		tmp += val[x] + " ";
	}
	setVal(id, tmp);
}

function tokenize(str, climit) {
	var counter = 0;
	var tmp = "";
	for (var x = 0; x < str.length; x++) {
		if (counter == climit) {
			tmp += " ";
			counter = 0;
		}
		
		tmp += str.charAt(x);
		counter++;
	}
	return tmp;
}

function check_date(field) {
	var checkstr = "0123456789";
	var Datevalue = "";
	var DateTemp = "";
	var seperator = ".";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	DateValue = field;
	/* Delete all chars except 0..9 */
	for (i = 0; i < DateValue.length; i++) {
		if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
			DateTemp = DateTemp + DateValue.substr(i,1);
		}
	}
	DateValue = DateTemp;
	/* Always change date to 8 digits - string*/
	/* if year is entered as 2-digit / always assume 20xx */
	if (DateValue.length == 6) {
		DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2);
	}
	if (DateValue.length != 8) {
		err = 19;
	}
	/* year is wrong if year = 0000 */
	year = DateValue.substr(4,4);
	if (year == 0) {
		err = 20;
	}
	/* Validation of month*/
	month = DateValue.substr(2,2);
	if ((month < 1) || (month > 12)) {
		err = 21;
	}
	/* Validation of day*/
	day = DateValue.substr(0,2);
	if (day < 1) {
		err = 22;
	}
	/* Validation leap-year / february / day */
	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
		leap = 1;
	}
	if ((month == 2) && (leap == 1) && (day > 29)) {
		err = 23;
	}
	if ((month == 2) && (leap != 1) && (day > 28)) {
		err = 24;
	}
	/* Validation of other months */
	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
		err = 25;
	}
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
		err = 26;
	}
	/* if 00 ist entered, no error, deleting the entry */
	if ((day == 0) && (month == 0) && (year == 00)) {
		err = 0; day = ""; month = ""; year = ""; seperator = "";
	}
	/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
	if (err == 0) {
		return true;
	}
	/* Error-message if err != 0 */
	else {
		return false;
	}
}

function textCounter(id, limit) {
	var comment = getVal(id);
	var len = comment.length;
	
	if (len>limit) {
		var newComments = comment.substring(0, limit);
		setVal(id, newComments);
	}
	displayCounter(id, limit);
}

function displayCounter(id, limit) {
	var comment = getVal(id);
	var len = comment.length;
	var dif = limit - len;
	setXHTML("counter_"+id, dif + " character(s) left");
}

function createDynamicDiv(p_div, pre, c_id, val) {
	var ni = document.getElementById(p_div);
	var num = document.getElementById(c_id);
	var newdiv = document.createElement('div');
	divIdName = pre + num.value;
	var id = num.value;
	
	newdiv.setAttribute("id", divIdName);
	
	if (num.value == 0) {
		num.value = parseInt(num.value)+2;
	} else {
		num.value = parseInt(num.value)+1;
	}
	
	var str = "";
		str += "<div>";
		str += "<table width='100%'>";
		str += "<tr>";
		str += "<td width='26%' height='28' align='right' valign='middle' class='tabletext'></td>";
		str += "<td width='74%' height='28' align='left' valign='middle'>";
		str += "<div class='small_link' onclick='removeDynamicDiv(\""+ p_div +"\", \""+ divIdName +"\")'>Remove</div></td>";
		str += "</tr></table></div>";
	
	newdiv.innerHTML = val + str;
	ni.appendChild(newdiv);
	initAutoList(p_div);
}

function createDynamicDivIM(p_div, pre, c_id, val) {
	var ni = document.getElementById(p_div);
	var num = document.getElementById(c_id);
	var newdiv = document.createElement('div');
	divIdName = pre + num.value;
	var id = num.value;
	var im_list = "im_list_" + num.value;
	
	newdiv.setAttribute("id", divIdName);
	
	if (num.value == 0) {
		num.value = parseInt(num.value)+2;
	} else {
		num.value = parseInt(num.value)+1;		
	}
	
	var str = "";
	str += "<table width='100%'>";
		str += "<tr>";
		str += "<td width='26%' height='28' align='right' valign='middle' class='tabletext'></td>";
		str += "<td width='74%' height='28' align='left' valign='middle'>";
		str += "<div class='small_link' onclick='removeDynamicDiv(\""+ p_div +"\", \""+ divIdName +"\")'>Remove</div></td>";
		str += "</tr></table>";
	
	
	newdiv.innerHTML = val;
	ni.appendChild(newdiv);
	setHTML(im_list, str);
	initAutoList(p_div);
}

function createDynamicDivEmail(p_div, pre, c_id, val) {
	var ni = document.getElementById(p_div);
	var num = document.getElementById(c_id);
	var newdiv = document.createElement('div');
	divIdName = pre + num.value;
	var id = num.value;
	var im_list = "email_list_" + num.value;
	
	newdiv.setAttribute("id", divIdName);
	
	if (num.value == 0) {
		num.value = parseInt(num.value)+2;
	} else {
		num.value = parseInt(num.value)+1;		
	}
	
	var str = "";
	str += "<div><table width='100%'><tr><td width='74%' height='28' align='left' valign='middle'><a class='small_link' onclick='removeDynamicDiv(\""+ p_div +"\", \""+ divIdName +"\")'>Remove</a></td></tr></table></div>";
	
	newdiv.innerHTML = val;
	ni.appendChild(newdiv);
	setHTML(im_list, str);
	initAutoList(p_div);
}

function removeDynamicDiv(p_id, t_id) {
	var parentDiv = document.getElementById(p_id);
	var childDiv = document.getElementById(t_id);
	
	parentDiv.removeChild(childDiv);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function imageValidator(val) {
	var ext = val.substring( val.lastIndexOf(".", val.length - 1));
	ext = ext.toLowerCase();
	if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" ) {
		return true;
	} else {
		return false;
	}
}

function getElm(id) {
		return document.getElementById(id);
}


function changeLocation(val) {
	if (val == 0) {
		redirect("index.php?req=manage_events_frame");
	} else {
		redirect("index.php?req=home&event_id="+val);
	}
}

function updateUserSettings(email, password) {
	// Set the default pop-up dialog values for those not supplied.

	// Retrieve the dialog contents via AJAX, and display the dialog.
	var ajax = new Ajax();
	ajax.responseType = Ajax.RAW;
	ajax.requireLogin = true;
	ajax.ondone = function(data) {
		if (data == "1") {
			hideDiv("dialog-loader");
			showDiv("success_message");
			setTimeout(	function () {dialog.hide()},  "1000");
		}
	}
	
	var params={"email": email,  "userid": "<?=$user?>"};
	ajax.post('<?=$iframepath."ajaxUserSettings.php"?>',params);
}

var dialog;	
function showDialog() {
	dialog = new Dialog().showChoice("Set Email", dialog_desc, "OK", "Cancel");
	dialog.onconfirm = function() {
		setXHTML("email_div", "");
		
		if (getVal("email") == "") {
			setXHTML("email_div", "Please enter email address.");
			return false;
		}  else if (getVal("email") != "" ) {
			var email = getVal("email");
			
			if (email.indexOf('@')==-1) {
				setXHTML("email_div", "Incorrect email address.")
				return false;
			} else {
				tmp = email.split("@");
				
				if (tmp[1].indexOf('.')==-1) {
					setXHTML("email_div", "Incorrect email address.")
					return false;
				}
			}
		}
		
		hideDiv("dialog_content");
		showDiv("dialog-loader");
		updateUserSettings(getVal("email"));
		return false;
	}
}

var fan_dialog;
function confirmGift(userid, p_id, step) {
	fan_dialog = new Dialog().showChoice("Confirm Gift", add_fan_dialog, "Yes", "Cancel");
	
	showDiv("msg_"+step);

	fan_dialog.onconfirm = function() {
		hideDiv("fan_dialog_content");
		showDiv("fan-dialog-loader");
		var ajax = new Ajax();
		ajax.responseType = Ajax.RAW;
		ajax.requireLogin = true;
		ajax.ondone = function(data) {
			if (data == "1") {
				hideDiv("fan-dialog-loader");
				showDiv("fan_success_message");
						
				if (step == 0) {
					hideDiv("c_p_"+p_id);
					showDiv("r_p_"+p_id);
				} else {
					hideDiv("c_p_"+p_id);
					hideDiv("r_p_"+p_id);
					showDiv("end_"+p_id);						
				}
				
				setTimeout(	function () { fan_dialog.hide() },  "2000" );
			} else {
				hideDiv("fan-dialog-loader");
				showDiv("fan_error_message");
				setTimeout(	function () { fan_dialog.hide() },  "2000" );
			}
		}
		
		var params={"userid": userid, "user": "<?=$user?>", "step": step, "p_id": p_id};
		ajax.post('<?=$iframepath."ajaxGiftNotification.php"?>',params);
		
		return false;
	}
}

function toggleDiv(id) {
	showDiv("c_p_"+id);
	hideDiv("r_p_"+id);
}

function isDate(txtDate) {
	var objDate;  // date object initialized from the txtDate string
	var mSeconds; // milliseconds from txtDate
	
	// date length should be 10 characters - no more, no less
	if (txtDate.length != 10) return false;
	
	// extract day, month and year from the txtDate string
	// expected format is mm/dd/yyyy
	// subtraction will cast variables to integer implicitly
	var day   = txtDate.substring(8, 10)  - 0;
	var month = txtDate.substring(5, 7)  - 1; // because months in JS start with 0
	var year  = txtDate.substring(0, 4) - 0;
	
	// third and sixth character should be /
	if (txtDate.substring(4,5) != '/') return false;
	if (txtDate.substring(7,8) != '/') return false;
	
	// test year range
	if (year < 999 || year > 3000) return false;
	
	// convert txtDate to the milliseconds
	mSeconds = (new Date(year, month, day)).getTime();
	
	// set the date object from milliseconds
	objDate = new Date();
	objDate.setTime(mSeconds);
	
	// if there exists difference then date isn't valid
	if (objDate.getFullYear() != year)  return false;
	if (objDate.getMonth()    != month) return false;
	if (objDate.getDate()     != day)   return false;
	
	// otherwise return true
	return true;
}