/********************/
/* Cookie Functions */
/********************/
function setCookie(name, value, expires, path, domain, secure) {
	domain = '.photostockplus.com';
	var curCookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : '');
	document.cookie = curCookie;
}
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + '=';
	var begin = dc.indexOf('; ' + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) { return null; }
	} else { begin += 2; }
	var end = document.cookie.indexOf(';', begin);
	if (end == -1) { end = dc.length; }
	return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		value = '';
		domain = '.photostockplus.com';
		expires = new Date();
		secure = '';
		setCookie(name, value, expires, path, domain, secure);
	}
}
function checkCookies() {
	expiry = new Date();
	expiry.setMonth(expiry.getMonth()+1);
	setCookie('cookies_enabled', 1, expiry, '/', '.photostockplus.com');
	cookies_enabled = getCookie('cookies_enabled');
	deleteCookie('cookies_enabled', '/', '.photostockplus.com');
	if(!cookies_enabled) {
		alert('Cookies are disabled or not supported by your browser or your security settings are too high');
		document.location.href = '/no_cookies.php';
	}
	return cookies_enabled;
}

/************************/
/* Photo Book Functions */
/************************/
function selectPhotoInSelectorForPhotoBook(photo_id,checked) {
	if(checked) { addPhotoToPhotoBookCookie(photo_id); }
	else { removePhotoToPhotoBookCookie(photo_id) }
}
function addPhotoToPhotoBookCookie(photo_id) {
	if(!in_array(photo_id,photo_ids)) { photo_ids[photo_ids.length] = photo_id; }
	ck_photo_ids = photo_ids.join(',');
	now = new Date();
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookie( 'add_to_photobook', ck_photo_ids, now, '/', '.photostockplus.com', '' );
}
function removePhotoToPhotoBookCookie(photo_id) {
	tmp = new Array();
	for(i=0; i < photo_ids.length; i++) { if(photo_ids[i] != photo_id) { tmp[tmp.length] = photo_ids[i]; } }
	photo_ids = tmp;
	ck_photo_ids = photo_ids.join(',');
	now = new Date();
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookie( 'add_to_photobook', ck_photo_ids, now, '/', '.photostockplus.com', '' );
}

/******************/
/* Cart Functions */
/******************/
/*function addFavoritesToCart(favorite_id,domain,favorite_nb_photos,viewCartLink) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		setCookie( 'favcart_fav', getCookie('favcart_fav')+ ',' + favorite_id, now, '/', '.photostockplus.com', '' );
		showCartLinks(viewCartLink);
		cart_nb_photos += photos_not_in_cart;
		updateCartText(cart_nb_photos,cart_nb_items);
		photos_not_in_cart = 0;
	}
}*/
function addLightboxToCart(lightbox_id,domain,lightbox_nb_photos,viewCartLink) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		setCookie( 'favcart_lb', getCookie('favcart_lb')+ ',' + lightbox_id, now, '/', '.photostockplus.com', '' );
		showCartLinks(viewCartLink);
		cart_nb_photos += photos_not_in_cart;
		updateCartText(cart_nb_photos,cart_nb_items);
		photos_not_in_cart = 0;
	}
}
function addAlbumToCart(album_id,domain,album_nb_photos,viewCartLink) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		setCookie( 'favcart_a', getCookie('favcart_a')+ ',' + album_id, now, '/', '.photostockplus.com', '' );
		showCartLinks(viewCartLink);
		cart_nb_photos += photos_not_in_cart;
		updateCartText(cart_nb_photos,cart_nb_items);
		photos_not_in_cart = 0;
	}
}
function addEventToCart(user_id,album_ids,domain,album_nb_photos,viewCartLink) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		for(i=0; i < album_ids.length; i++) { setCookie( 'favcart_a', getCookie('favcart_a')+ ',' + user_id + '_' + album_ids[i], now, '/', '.photostockplus.com', '' ); }
		showCartLinks(viewCartLink);
		cart_nb_photos += photos_not_in_cart;
		updateCartText(cart_nb_photos,cart_nb_items);
		photos_not_in_cart = 0;
	}
}
function addPhotoToCart(photo_id,domain,viewCartLink) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		setCookie( 'favcart', getCookie('favcart')+ ',' + photo_id, now, '/', '.photostockplus.com', '' );
		showCartLink(photo_id,viewCartLink);
		cart_nb_photos += 1;
		photos_not_in_cart -= 1;
		updateCartText(cart_nb_photos,cart_nb_items);
	}
}
function showCartLink(photo_id,viewCartLink) {
	tag_cart_img = document.getElementById('a_tag_cart_img_'+photo_id);
	tag_cart = document.getElementById('a_tag_cart_'+photo_id);
	if(tag_cart_img && tag_cart) {
		tag_cart_img.src = tag_cart_img.src.replace('add_to_cart2.gif','view_cart3.gif');
		tag_cart.href = viewCartLink;
		tag_cart.target = '_top';
	}
}
function showCartLinks(viewCartLink) {
	if(pagePhotos.length > 0 && pagePhotos[0] != '') {
		for(i=0; i < pagePhotos.length; i++) {
			if(pagePhotos[i]) { showCartLink(pagePhotos[i],viewCartLink); }
		}
	} else { alert('No photos to add'); }
}
function showCartModule() {
	if((cart_nb_photos > 0 || cart_nb_items > 0) && !dont_show_cart_box) {
		var cartModuleLeftHTML = '<div align=center><table width="100%" border="0" align="center" cellpadding="3" cellspacing="0" class="box-left-shoppingcart">'+
		'<tr><td class="box-left-shoppingcart-header">My Shopping Cart</td></tr>'+
		'<tr><td height="3"></td></tr>'+
		'<tr><td class="border-blk">'+
		'<span id="span_cartText"></span><br /><br />'+
		'<a href="cart.php"><img src="'+img_server+'/img/b_viewcart.gif" width="184" height="23" border="0"></a>'+
		'</td></tr>'+
		'</table></div><br />';

		var cartModuleLeftObj = document.getElementById("span_cartModuleLeft");
		if(cartModuleLeftObj) { cartModuleLeftObj.innerHTML = cartModuleLeftHTML; }

		var cartModuleBoxHTML = 
			'<table width="100%" border="0" align="center" cellpadding="3" cellspacing="0" class="box-shoppingcart">'+
			//'<tr><td height="4" colspan="2"></td></tr>'+
			'<tr><td colspan="2" align="left" class="box-shoppingcart-header">My Shopping Cart</td></tr>'+
			'<tr>'+
			'<td align=left><span id="#SPAN_ID#"></span></td>'+
			'<td align=right><a href=\"javascript:goToCart();\"><img src=\"'+img_server+'/img/view_cart3.gif\" border=\"0\"></a></td>'+
			'</tr>'+
			'</table>';
		cartModuleBoxHTML = 
			'<div class="box-shoppingcart">'+
			'<div class="box-shoppingcart-header">My Shopping Cart</div>'+
			'<div style="float:left" id="#SPAN_ID#"></div>'+
			'<div style="text-align: right;"><a href="javascript:goToCart();"><img src=\"'+img_server+'/img/view_cart3.gif\" border=\"0\"></a></div>'+
			'</tr>'+
			'</div>';

		var cartModuleObj = document.getElementById("span_cartModule");
		if(cartModuleObj) {
			//~ cartModuleHTML = cartModuleBoxHTML.replace('#SPAN_ID#','span_cartText');
			//~ cartModuleObj.innerHTML = cartModuleHTML;
			cartModuleObj.innerHTML = cartModuleBoxHTML.replace('#SPAN_ID#','span_cartText');
		}
		var cartModuleTmplObj = document.getElementById("span_cartModuleTmpl");
		if(cartModuleTmplObj) {
			cartModuleTmplHTML = cartModuleBoxHTML.replace('#SPAN_ID#','span_cartText');
			cartModuleTmplObj.innerHTML = cartModuleTmplHTML;
		}
		var cartModule2Obj = document.getElementById("span_cartModule2");
		if(cartModule2Obj) {
			cartModule2HTML = cartModuleBoxHTML.replace('#SPAN_ID#','span_cartText2');
			cartModule2Obj.innerHTML = cartModule2HTML;
		}
		var cartModule2TmplObj = document.getElementById("span_cartModule2Tmpl");
		if(cartModule2TmplObj) {
			cartModule2TmplHTML = cartModuleBoxHTML.replace('#SPAN_ID#','span_cartText2');
			cartModule2TmplObj.innerHTML = cartModule2TmplHTML;
		}
	}
}
function hideCartModule() {
	if(cart_nb_photos < 1 && cart_nb_items < 1) {
		/*cartModuleLeftHTML = '';
		cartModuleHTML = '';
		cartModule2HTML = '';
		cartModuleTmplHTML = '';
		cartModule2TmplHTML = '';*/
		
		var cartModuleLeftObj = document.getElementById("span_cartModuleLeft");
		var cartModuleObj = document.getElementById("span_cartModule");
		var cartModule2Obj = document.getElementById("span_cartModule2");
		var cartModuleTmplObj = document.getElementById("span_cartModuleTmpl");
		var cartModule2TmplObj = document.getElementById("span_cartModule2Tmpl");
		
		if(cartModuleLeftObj) 	{ cartModuleLeftObj.innerHTML 	= ''/*cartModuleLeftHTML*/; }
		if(cartModuleObj) 		{ cartModuleObj.innerHTML 		= ''/*cartModuleHTML*/; 	}
		if(cartModule2Obj)		{ cartModule2Obj.innerHTML 		= ''/*cartModule2HTML*/; 	}
		if(cartModuleTmplObj)	{ cartModuleTmplObj.innerHTML 	= ''/*cartModuleTmplHTML*/; }
		if(cartModule2TmplObj)	{ cartModule2TmplObj.innerHTML	= ''/*cartModule2TmplHTML*/;}
	}
}
function updateCartText(final_nb_photos,final_nb_items) {
	if(!cartModuleShowing && (final_nb_photos > 0 || final_nb_items > 0)) { showCartModule(); cartModuleShowing = 1; }
	else { hideCartModule(); cartModuleShowing = 0; }
	var str = 'You have '+final_nb_photos+' photo'+((final_nb_photos==1)?'':'s')+' with '+final_nb_items+' item'+((final_nb_items==1)?'':'s')+' in your cart';
	var cartTextObj = document.getElementById("span_cartText");
	var cartText2Obj = document.getElementById("span_cartText2");
	if(cartTextObj) { cartTextObj.innerHTML = str; }
	if(cartText2Obj) { cartText2Obj.innerHTML = str; }
}
function goToCart() {
	document.location.href='/cart.php?tmpl='+tmpl_id+'&user_id='+user_id+'&event='+event_id+'';
}
/*
function showPrintableInvoice(site_url,order_id) {
	invoiceWin = openPopup(site_url+'/includes/modules/view_invoice.php?oid='+order_id+'&viewonly=1',700,500); // belong to a commented code
	//invoiceWin.focus();
}
*/
function printInvoice() {
	print();
	return false;
}
function printPhotoInfo() {
	print();
	return false;
}

/***********************/
/* Favorites Functions */
/***********************/
/* DROPME function addLightboxToFavorites(lightbox_id,domain,lightbox_nb_photos,viewFavoritesLink) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		setCookie( 'favlist_lb', getCookie('favlist_lb')+ ',' + lightbox_id, now, '/', '.photostockplus.com', '' );
		showFavoritesLinks(viewFavoritesLink);
		fav_nb_photos += 1;
		updateFavoritesText(fav_nb_photos);
	}
}*/

/*
function addAlbumToFavorites(album_id,domain,album_nb_photos,viewFavoritesLink) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		setCookie( 'favlist_a', getCookie('favlist_a')+ ',' + album_id, now, '/', '.photostockplus.com', '' );
		showFavoritesLinks(viewFavoritesLink);
		fav_nb_photos += 1;
		updateFavoritesText(fav_nb_photos);
	}
}
function addPhotoToFavorites(photo_id,domain) {
	if(checkCookies()) {
		now = new Date();
		now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
		setCookie( 'favlist', getCookie('favlist')+ ',' + photo_id, now, '/', '.photostockplus.com', '' );
		showFavoritesLink(photo_id);
		fav_nb_photos += 1;
		updateFavoritesText(fav_nb_photos);
	}
}
function showFavoritesLink(photo_id) {
	document.getElementById('a_tag_fav_'+photo_id).innerHTML = document.getElementById('a_tag_fav_'+photo_id).innerHTML = 'Remove from Favorites';
	document.getElementById('a_tag_fav_'+photo_id).href = 'javascript:removeFav('+ photo_id +')';
	//document.getElementById('a_tag_fav_'+photo_id).target = '_top';
}
function showFavoritesLinks(viewFavoritesLink) {
	for(i=0; i < pagePhotos.length; i++) {
		showFavoritesLink(pagePhotos[i],viewFavoritesLink);
	}
}
function showFavoritesModule() {
	if(fav_nb_photos > 0) {
		favoritesModuleLeftHTML = '<table width="100%" border="0" align="center" cellpadding="3" cellspacing="0">'+
		'<tr><td class="border-blk">'+
		'<a href="javascript:goToFavorites();"><img src="'+img_server+'/img/view_favorites2.gif" width="184" height="23" border="0"></a>'+
		'</td></tr>'+
		'</table><br />';

		favoritesModuleLeftObj = jQuery('#span_favoritesModuleLeft');
		if(favoritesModuleLeftObj && favoritesModuleLeftObj.html() == '') { 
			favoritesModuleLeftObj.hide();
			favoritesModuleLeftObj.html(favoritesModuleLeftHTML);
			favoritesModuleLeftObj.show('slow');
		}
	}
}
function hideFavoritesModule() {
	if(fav_nb_photos < 1) {
		favoritesModuleLeftHTML = '';

		favoritesModuleLeftObj = jQuery('#span_favoritesModuleLeft');
		
		if(favoritesModuleLeftObj) { 
			favoritesModuleLeftObj.hide('fast'); 
			favoritesModuleLeftObj.html('');
		}
	}
}
function updateFavoritesText(final_nb_photos) {
	if(!favoritesModuleShowing && final_nb_photos > 0) { showFavoritesModule(); favoritesModuleShowing = 1; }
	else { hideFavoritesModule(); favoritesModuleShowing = 0; }
	str = 'You have '+final_nb_photos+' photo'+((final_nb_photos==1)?'':'s')+' in your favorites';
	favoritesTextObj = document.getElementById("span_favoritesText");
	favoritesText2Obj = document.getElementById("span_favoritesText2");
	if(favoritesTextObj) { favoritesTextObj.innerHTML = str; }
	if(favoritesText2Obj) { favoritesText2Obj.innerHTML = str; }
}
function goToFavorites() {
	document.location.href='/favorites.php?tmpl='+tmpl_id+'&user_id='+user_id+'&event='+event_id+'';
}

function removeFav(photo_id) {
		jQuery('#a_tag_fav_'+photo_id).attr('href','#');
		jQuery('#a_tag_fav_'+photo_id).html('Please wait...');
		jQuery.ajax({
			method: 'get',
			url: 'favorites.php',
			data: 'fav_photo_id='+photo_id+'&action=remove',
			success: function(ret) {
				now = new Date();
				now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
				fav_nb_photos-=1;
				if ((old_cookie=getCookie('Favorites')) != null)
					setCookie( 'Favorites', old_cookie.replace(photo_id,''), now, '/', '.photostockplus.com', '' );
				if ((old_cookie=getCookie('favlist')) != null)
					setCookie( 'favlist', old_cookie.replace(photo_id,''), now, '/', '.photostockplus.com', '' );
				jQuery('#a_tag_fav_'+photo_id).html('Add Favorites');
				jQuery('#a_tag_fav_'+photo_id).attr('href','javascript:addPhotoToFavorites('+ photo_id +',\'\')');
				updateFavoritesText(fav_nb_photos);
			}
		});	
}

function destroyFav(photo_id) {
	removeFav(photo_id);
	jQuery('#block_fav_'+photo_id).hide('fast', function(){jQuery(this).remove();});
}
*/

/*********************/
/* Coupons Functions */
/*********************/
/*
function showAvailableCouponsList(site_url) {
	couponsWin = openPopup(site_url+'/includes/modules/coupons_list.php',800,500); // belong to a commented code
	couponsWin.focus();
}
*/
function printAvailableCouponsList() {
	print();
	return false;
}

/******************/
/* Misc Functions */
/******************/
function checkPhoto(checked,photo_id) {
	return true;
}
function print_r( array, return_val, prefix_str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Ben Bryan
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
    
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if (obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj == null || obj == undefined) {
            str = '';
        } else {
            str = obj.toString();
        }
 
        return str;
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) { 
            str += pad_char; 
        };
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);
 
    if (return_val !== true) {
        document.write("<pre>" + prefix_str + output + "</pre>");
        return true;
    } else {
        return output;
    }
}
//function sleep(ms) { i=0; while(i<ms){i++;} }
function sleep(s) {
	Date.ONE_SECOND = 1000
	Date.ONE_MINUTE = Date.ONE_SECOND * 60
	Date.ONE_HOUR = Date.ONE_MINUTE * 60
	Date.ONE_DAY = Date.ONE_HOUR * 24
	s = s * Date.ONE_SECOND
	var then = new Date(new Date().getTime() + s);
	while (new Date() < then) {}
}
function genResizeImgDim(w,h,cmpw,cmph,resizeUp,round) {
	round=(round!=0)?1:0;
	var arr = new Array();
	if(resizeUp) {
		if(w < cmpw) {
			dimRatio = (w/cmpw);
			w = (w/dimRatio);
			h = (h/dimRatio);
		}
		if(h < cmph) {
			dimRatio = (h/cmph);
			w = (w/dimRatio);
			h = (h/dimRatio);
		}
	} else {
		if(w > cmpw) {
			dimRatio = (w/cmpw);
			w = (w/dimRatio);
			h = (h/dimRatio);
		}
		if(h > cmph) {
			dimRatio = (h/cmph);
			w = (w/dimRatio);
			h = (h/dimRatio);
		}
	}
	arr = new Array(w,h);
	if(round) {
		arr[0] = Math.round(arr[0]);
		arr[1] = Math.round(arr[1]);
	}
	return arr;
}
function genSwapImgDim(w,h) {
	arr = new Array(h,w);
	return arr;
}
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(/\\0/g,'\0');
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	return str;
}
function URLEncode(str) {
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +			// Numeric
			"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
			"abcdefghijklmnopqrstuvwxyz" +
			"-_.!~*'()";			// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var plaintext = str;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
		if (ch == " ") {
			encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
			encoded += ch;
		} else {
			var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				alert( "Unicode Character '" 
					+ ch 
					+ "' cannot be encoded using standard URL encoding.\n" +
					"(URL encoding only supports 8-bit characters.)\n" +
					"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return str;
}
function URLEncode2(str) {
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +			// Numeric
			"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
			"abcdefghijklmnopqrstuvwxyz" +
			"-_.!~*'()";			// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var plaintext = str;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
		if (ch == " ") {
			encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
			encoded += ch;
		} else {
			var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				alert( "Unicode Character '" 
					+ ch 
					+ "' cannot be encoded using standard URL encoding.\n" +
					"(URL encoding only supports 8-bit characters.)\n" +
					"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return encoded;
}
function URLDecode(str) {
	// Replace + with ' '
	// Replace %xx with equivalent character
	// Put [ERROR] in output if %xx is invalid.
	var HEXCHARS = "0123456789ABCDEFabcdef"; 
	var encoded = str;
	var plaintext = "";
	var i = 0;
	while (i < encoded.length) {
		var ch = encoded.charAt(i);
		if (ch == "+") {
			plaintext += " ";
			i++;
		} else if (ch == "%") {
			if (i < (encoded.length-2) && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
			plaintext += ch;
			i++;
		}
	}
	return str;
}
function URLDecode2(str) {
	// Replace + with ' '
	// Replace %xx with equivalent character
	// Put [ERROR] in output if %xx is invalid.
	var HEXCHARS = "0123456789ABCDEFabcdef"; 
	var encoded = str;
	var plaintext = "";
	var i = 0;
	while (i < encoded.length) {
		var ch = encoded.charAt(i);
		if (ch == "+") {
			plaintext += " ";
			i++;
		} else if (ch == "%") {
			if (i < (encoded.length-2) && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
			plaintext += ch;
			i++;
		}
	}
	return plaintext;
}
function number_format(number,dec) {
	var num = new NumberFormat();
	num.setInputDecimal('.');
	num.setNumber(number);
	num.setPlaces(dec);
	num.setCurrencyValue('$');
	num.setCurrency(false);
	num.setCurrencyPosition(num.LEFT_OUTSIDE);
	num.setNegativeFormat(num.LEFT_DASH);
	num.setNegativeRed(false);
	num.setSeparators(true, ',', ',');
	return num.toFormatted();
}
function onlyNumbers(e) {
	var unicode=e.charCode? e.charCode : e.keyCode
	if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
		if (unicode<48||unicode>57) { return false; } //disable key press if not a number
	}
	return true;
}
function date_format(dateObj) {
	var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var a = new Array("","st","nd","rd","th","th","th","th","th","th","th","st","nd","rd","th","th","th","th","th","th","th","st","nd","rd","th","th","th","th","th","th","th","st");
	return months[dateObj.getMonth()]+' '+dateObj.getDate()+a[dateObj.getDate()]+', '+dateObj.getFullYear();
}
function in_array(arr,val) {
	for(i=0; i < arr.length; i++) {
		if(arr[i] == val) { return true; }
	}
	return false;
}
// Removes leading whitespaces
function ltrim(value) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
// Removes ending whitespaces
function rtrim(value) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}
// Removes leading and ending whitespaces
function trim(value) {
	return ltrim(rtrim(value));
}

// This function shows/hides an overlapping div element when processing
function toggleProcessingWindow(show) {
	var ie5=document.all&&document.getElementById;
	var ns6=document.getElementById&&!document.all;
	
	initialX = (ns6)?window.innerWidth:iecompattest().clientWidth;
	initialX -= parseInt(document.getElementById('processingrequest').style.width);
	initialX = (initialX < 1)?0:initialX/2;
	
	initialY = (ns6)?window.innerHeight:iecompattest().clientHeight;
	initialY -= parseInt(document.getElementById('processingrequest').style.height);
	initialY = (initialY < 1)?0:initialY/2;
	initialY += (ns6)?window.pageYOffset:iecompattest().scrollTop;
	
	document.getElementById("processingrequest").style.left=initialX+"px";
	document.getElementById("processingrequest").style.top=initialY+"px";
	
	visibility = (show)?'visible':'hidden';
	display = (show)?'block':'none';
	document.getElementById('processingrequest').innerHTML = (show)?'<table width="185" height="90"  border="0" cellpadding="1" cellspacing="1" bgcolor="#CCCCCC">'+
'<tr>'+
'<td height="88">'+
'<table width="100%" height="100%"  border="0" cellpadding="0" cellspacing="0">'+
'<tr><td width="185" height="36" bgcolor="#FFFFFF"><div align="center"><p>Processing your request...</p></div></td></tr>'+
'<tr><td height="32" valign="top" bgcolor="#FFFFFF"><div align="center"><img src="'+img_server+'/img/processing.gif" width="124" height="14"></div></td></tr>'+
'</table>'+
'</td>'+
'</tr>'+
'</table>':'';
	document.getElementById('processingrequest').style.display = display;
	document.getElementById('processingrequest').style.visibility = visibility;
}

function iecompattest(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function getUimgDirPath(val) {
	file_path = "";
	max_dir_levels = val.length-getUimgDirPath_leftover;
	max_dir_levels = (max_dir_levels < 1)?val.length:max_dir_levels;
	for(i=0; i < max_dir_levels; i++) { file_path += ((file_path.length > 0)?"/":"")+val.charAt(i); }
	return file_path;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') { window.onload = func; }
  else {
    window.onload = function() {
      if (oldonload) { oldonload(); }
      func();
    }
  }
}

/********************/
/* Unload pop-under */
/********************/
/*
function clickHandler(e) {
	exiting = 0;
	return true;
}
function onUnloadFunc(logged_in) {
	return;
	//if(exiting && !logged_in && !Get_Cookie('unload_warning')) openPopup("/unload.php",560,505);
}
document.onclick = clickHandler;
var exiting = 1;
*/

function updateDOM(inputField) {
	// if the inputField ID string has been passed in, get the inputField object
	if (typeof inputField == 'string') {
		inputField = document.getElementById(inputField);
	}
	
	if (inputField.type == 'select-one') {
		for (var i=0; i<inputField.options.length; i++) {
			if (i == inputField.selectedIndex) {
				inputField.options[inputField.selectedIndex].setAttribute('selected','selected');
			}
		}
	} else if (inputField.type == 'text') {
		inputField.setAttribute('value',inputField.value);
	} else if (inputField.type == 'textarea') {
		inputField.setAttribute('value',inputField.value);
		inputField.innerHTML = inputField.value;
	} else if ((inputField.type == 'checkbox') || (inputField.type == 'radio')) {
		if (inputField.checked) {
			inputField.setAttribute('checked','checked');
		} else {
			inputField.removeAttribute('checked');
		}
	}
}


/*************/
/* Variables */
/*************/
var thumb_max = 180;
var large_max = 500;

// Fit border is a percentage value
// Borders left and right will each be 3.5% of the full width
// Borders top and bottom will each be 3.5% of the full height
var fit_border = 3.5;

/* XXX: not used anymore ?
var fitBorder_o = Math.round(large_max*(fit_border/100));
*/
var cropBorder_o = 2; // in pixels
var cart_nb_photos = 0;
var cart_nb_items = 0;
var fav_nb_photos = 0;
var updateCartText_done = 0;
var updateFavoritesText_done = 0; // TRASHME ? //
var cartModuleShowing = 0;
var favoritesModuleShowing = 0;
var tmpl_id = 0;
var user_id = '';
var event_id = '';
var photos_not_in_cart = 0;
var ie5 = (document.all && document.getElementById)?true:false;
var ns6 = (document.getElementById && !document.all)?true:false;

/*****************/
/* Floating DIVs */
/*****************/
// Code the "Processing your request..." floating div

/* XXX: moved in header.inc 
 document.write('<div id="processingrequest" align="center" style="position: absolute; display: none; left: 0px; top: 0px; width: 185px; height: 90px; z-index: 99999;"></div>');*/
// Code the "Cropping" floating div
//document.write('<div id="dwindow" style="position: absolute; background-color: white; cursor: hand; left: 0px; top: 0px; display: none; z-index: 9;" onMousedown="initializedrag(event)" onMouseup="stopdrag()" onSelectStart="return false"></div>');
// Code the floating styled popup div

/* XXX: moved in header.inc
 document.write('<div id="styled_popup" name="styled_popup" style="display: none; position: absolute; top: 150px; left: 50px; z-index: 99999;"></div>');*/