var clear="/shared/pngfix.gif" //path to clear.gif
pngfix=function(){var els=document.getElementsByTagName('*');var ip=/\.png/i;var i=els.length;while(i-- >0){var el=els[i];var es=el.style;if(el.src&&el.src.match(ip)&&!es.filter){es.height=el.height;es.width=el.width;es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";el.src=clear;}else{var elb=el.currentStyle.backgroundImage;if(elb.match(ip)){var path=elb.split('"');var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+'px';es.backgroundImage='none';var elkids=el.getElementsByTagName('*');if (elkids){var j=elkids.length;if(el.currentStyle.position!="absolute")es.position='static';while (j-- >0)if(!elkids[j].style.position)elkids[j].style.position="relative";}}}}}

function redirect_url(url){
	window.location=url;
}

var image_zoom_timer = 0;
function image_zoom(id,speed,delay,w,h,step_w,step_h,div_w,div_h){
	var step_w = (step_w == null) ? 0 : step_w;
	var step_h = (step_h == null) ? 0 : step_h;
	var div_w  = (div_w == null) ? 0 : div_w;
	var div_h  = (div_h == null) ? 0 : div_h;
	var w = (w == null) ? 0 : w;
	var h = (h == null) ? 0 : h;
	if (!step_w) {
		w = $(id).width();	ow = w;
		h = $(id).height();	oh = h;
		if (!w) {
			setTimeout("image_zoom('"+id+"',"+speed+","+delay+")",2000);
			return;
		}
		ratio = w/h;
		if (w>h){
			step_w = 1;
			step_h = 1/ratio;
		} else {
			step_w = 1/ratio;
			step_h = 1;
		}
		step_w *= speed;
		step_h *= speed;
		div = $(id).parents("div").get(0).id;
		div_w = $('#'+div).width();
		div_h = $('#'+div).height();
		// firelog("image_zoom('"+id+"',"+speed+","+delay+","+w+","+h+","+step_w+","+step_h+","+div_w+","+div_h+")");
	}
	w = w - step_w;
	h = h - step_h;
	if (h>=div_h && w>=div_w) {
		$(id).width(w).height(h);
		window.status = "Img Zoom : timer : "+image_zoom_timer+" div_w "+div_w+" div_h "+div_h+" speed "+speed+" delay "+delay+ " w "+Math.floor(w)+"/"+ow+" h "+Math.floor(h)+"/"+oh+" step_w "+step_w+" step_h "+step_h+" ratio "+ratio;
		image_zoom_timer = setTimeout("image_zoom('"+id+"',"+speed+","+delay+","+w+","+h+","+step_w+","+step_h+","+div_w+","+div_h+")",delay);
	} else {
		//window.status = 'Zoom Complete';
	}
}

function image_zoom_cancel(){
	if (image_zoom_timer) {
		window.status = "Img Zoom : cancelled";
		clearTimeout(image_zoom_timer);
	}
}

function jcarousel_initCallback(carousel)
{
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}

function highlight_inputs() {
	$(".input_button").live('mouseover', function(){
		$(this).addClass('input_button_selected');
	});
	$(".input_button").live('mouseout', function(){
		$(this).removeClass('input_button_selected');
	});
	elements = ".input_qty, .input_select, .input_text, .input_checkbox, .input_radio, .input_textarea";
	// detect IE not input_select, dissapears when you mouse off in IE */
	if (!$.support.leadingWhitespace) elements = ".input_qty, .input_text, .input_checkbox, .input_radio, .input_textarea";
	$(elements).live('mouseover', function(){ 
		$(this).addClass("input_hover");
	});
	$(elements).live('mouseout', function(){ 
		$(this).removeClass("input_hover");
	});
}

function firelog(s){
	if (typeof(console)!="undefined") console.log(s);
}

function checkId(id){
	id = id.replace("#","");
	if (!id) return;
	c = $('#'+id).length;
	//firelog("checkId "+id+" "+c);
	return (c > 0);
}

auto_div_height_animating = new Array;
function auto_div_height(id,monitor){
	if (auto_div_height_animating[id]) return;
	if (!checkId(monitor)) {
		firelog("auto_div_height : "+monitor+' removed from dom');
		return;
	}
	//firelog("auto_div_height : ('"+id+"','"+monitor+"')");
	container = id.replace('#','')+"_container";
	cid = "#"+container;
	if (!checkId(cid)) $(id).wrap("<div id='"+container+"'></div>");
	ch = $(cid).height();
	c  = $(id).height();
	if (c != ch){
		auto_div_height_animating[id] = true;
		firelog("auto_div_height : animating c "+c+" ch "+ch+" monitor "+monitor);
		$(cid).animate(
			{ height : c }, 500,
			function() {
				firelog("auto_div_height : animation complete "+monitor);
				auto_div_height_animating[id] = false;
				if ($(id).css('display') == 'none') $(id).fadeIn();
				setTimeout("auto_div_height('"+id+"','"+monitor+"')",500);
			}	
		);
	} else {
		$(cid).css('backgroundImage','none');
		if ($(id).css('display') == 'none') $(id).fadeIn();
		//firelog("auto_div_height : c "+c+" ch "+ch+" id "+id+" cid "+cid+" "+monitor);
		setTimeout("auto_div_height('"+id+"','"+monitor+"')",500);
	}
}

// stop ajax forms being submitted for invalid forms
function check_form(formData, jqForm, options){ 
	valid = $(options.id).valid();
	if (options.fadeout){
		if (valid) $(options.target).fadeOut();
		//else $(options.target).effect("highlight", { color: '#F00' }, 3000);
	}
	return valid;
}

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_itemList[idx - 1].html);
}

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);
}

function datePicker(id) {
	$("#"+id).datepicker({ 
		dateFormat: 'dd/mm/yy', 
		changeMonth: true,
		changeYear: true,
		showAnim: 'slideDown'
	});
}
function datePickerIPTC(id) {
	$("#"+id).datepicker({ 
		dateFormat: 'yymmdd', 
		changeMonth: true,
		changeYear: true,
		showAnim: 'slideDown'
	});
}

function centerDiv(div) {
	divW = $(div).width();
	divH = $(div).height();
	width  = $(window).width();
	height = $(window).height();
	x = (width/2)-(divW/2);
	y = (height/2)-(divH/2)+$(window).scrollTop();
	$(div).css('top',y).css('left',x);
	$(div).fadeIn();
}

function popup_div(img) {
	$('#popup_div').fadeOut().html("<img id='popup_img' src='/tmp'+img+'>");
	setTimeout("centerDiv('#popup_div')",2000);
}

function popup_div_no_fade(img) {
	$('#popup_div_no_fade').hide().html("<img id='popup_img' src='/tmp"+img+"'>");
	centerDiv('#popup_div_no_fade');
}

// required for $('#id').load('page.php?params=have spaces in them')
function urlencode (str) {
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };
 
    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();
 
    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

function id_check(){
	var allTags = document.body.getElementsByTagName('*');
	var ids = [];
	for (var tg = 0; tg< allTags.length; tg++) {
		var tag = allTags[tg];
		if (tag.id) {
			if (ids[tag.id] && tag.id != ',ilink' && tag.id != 'filename') ids.push(tag.id+'\n');
			else ids[tag.id] = 1;
		}
	}
	alert(ids);
}

function toggle_checkbox(id) {
	el = document.getElementById(id); 
	if (!el) {
		walert("Cannot set checkbox, no such id ["+id+"]");
		return;
	}
	el.value = 1-el.value;
}

function Height() {	return $(body).height(); }
function Width() {	return $(body).width(); }
function getHeight() { return Height(); }
function getWidth() { return Width(); }

function set_valid(nm,is_valid){
	return;
	e = document.getElementById("valid_"+nm);
	if (!e) {
		walert("Cannot find id to display error looking for valid_"+nm);
	} else {
		if (is_valid) e.innerHTML = "";
		else e.innerHTML = "<img alt='This field is required.' src='/shared/cart_warning.gif'>";
	}
}

function err_row(nm,s){
	set_valid(nm,false);
	nm = nm.replace('_',' ');
	return "<li>"+nm+" "+s+"</li>\n";
}

// validate + set_valid for old carts
function validate_form(formname){
	var txt = ""; 
	e = document.getElementById(formname);
	if (!e){
		walert("Cannot validate "+formname+" no such id.");
		return true;
	}
	check_password = false;
	fields = e.elements;
	password = confirm_password = "";
	for(i=0; i<fields.length; i++)
	{
		nm  = fields[i].name;
		id  = fields[i].id;
		val = fields[i].value;
//		txt = txt + id + " " + nm + " " + "[" + val + "]<br>";
		if (id.length<8) continue;
		s = id.slice(0,8);
		if (s!="id_valid") continue;
		set_valid(nm,true);
		fields[i].style.background='#FFFFFF';
		if (id=="id_valid_not_null" && val.length==0) {
			fields[i].style.background='#FF7777';
			txt = txt + err_row(nm,"is a mandatory field.");
		}
		if (id=="id_valid_email" && !echeck(val)){
			fields[i].style.background='#FF7777';
			txt = txt + err_row(nm,"is not a valid email address.");
		}
		if (id=="id_valid_credit_card" && !checkcreditcard(val)){
			fields[i].style.background='#FF7777';
			txt = txt + err_row(nm,"is not a valid credit card number.");
		}
		if (id=="id_valid_terms"){
			val = fields[i].checked;
			if (val==false){
				alert("You must accept our terms and conditions before you can place your order.");
				return;
			}
		}
		if (nm=="password") password = val;
		if (nm=="confirm_password") {
			check_password = true;
			confirm_password = val;
		}
	}
	if (check_password && (password != confirm_password)){
		txt = txt + err_row(nm,"your passwords do not match");
		set_valid("password",false);
		set_valid("confirm_password",false);
	}
	if (txt) {
		err.innerHTML=txt
		return false;
	} else err.innerHTML="";
	return true;
}

function saveFormId(fn){
	formId = document.getElementById(fn);
	if (formId) {
		$('#spinner').show();
		formId.submit();
	} else alert('cannot save: bad form id: '+fn);
}

function conf(s){
	return window.confirm(s);
}

var activeEditors = new Array()

function activateEditor(id) {
    //alert("activate "+id);
	activeEditors[activeEditors.length] = id;
    toggleEditor(id);
}

function deactivateEditors() {
	//alert('active '+activeEditors.length);
    for(x=0;x<activeEditors.length;x++) {
		walert("Removing editor "+x);
        toggleEditor(activeEditors[x])
    }
    activeEditors.length = 0;
}

// functions
function toggleEditor(id) {
	var elm = document.getElementById(id);
	if (!elm) {
		walert("no such id "+id);
		return;
	}
	if (tinyMCE.getInstanceById(id) == null){
		walert('add' + id);
		tinyMCE.execCommand('mceAddControl', false, id);
	} else {
		walert('focus' + id);
		tinyMCE.execCommand('mceFocus', false, id);
		walert('remove' + id);
		tinyMCE.execCommand('mceRemoveControl', false, id);
	}
} 

function popup(URL,w,h) {
	aWindow=window.open(URL, "thewindow", "toolbar=no, width="+w+", height="+h+", status=no, scrollbars=yes, resize=no, menubars=no");
}

function popup_full(URL,w,h) {
	aWindow=window.open(URL, "thewindow", "toolbar=no, width="+w+", height="+h+", status=yes, scrollbars=yes, resize=yes, menubars=no");
}

function popup_clean(URL,w,h) {
	aWindow=window.open(URL, "", "toolbar=no, width="+w+", height="+h+", status=no, scrollbars=no, resize=no, menubars=no");
}

function popup_scroll(URL,w,h) {
	aWindow=window.open(URL, "", "toolbar=no, width="+w+", height="+h+", status=no, scrollbars=yes, resize=no, menubars=no");
}

function putFocus(formInst, elementInst) {
	if (document.forms.length > 0) {
		if (document.forms[formInst].elements[elementInst]) {
			document.forms[formInst].elements[elementInst].focus();
		}
	}
}

function placeFocus() {
	if (document.forms.length > 0) {
		var field = document.forms[0];
		for (i = 0; i < field.length; i++) {
			if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type.toString().charAt(0) == "s")) {
				document.forms[0].elements[i].focus();
				break;
			}
		}
	}
}

function checkcreditcard(object_value){
	if (object_value.length == 0)
		return false;
	var white_space = " -";
	var creditcard_string="";
	var check_char;

	for (var i = 0; i < object_value.length; i++)
	{
		check_char = white_space.indexOf(object_value.charAt(i));
		if (check_char < 0)
			creditcard_string += object_value.substring(i, (i + 1));
	}	

	if (creditcard_string.length < 13 || creditcard_string.length > 19)
		return false;

	if (creditcard_string.charAt(0) == "+")
		return false;

	if (!_CF_checkinteger(creditcard_string))
		return false;

	var doubledigit = creditcard_string.length % 2 == 1 ? false : true;
	var checkdigit = 0;
	var tempdigit;

	for (var i = 0; i < creditcard_string.length; i++)
	{
		tempdigit = eval(creditcard_string.charAt(i));

		if (doubledigit)
		{
			tempdigit *= 2;
			checkdigit += (tempdigit % 10);

			if ((tempdigit / 10) >= 1.0)
				checkdigit++;

			doubledigit = false;
		}
		else
		{
			checkdigit += tempdigit;
			doubledigit = true;
		}
	}	
	return (checkdigit % 10) == 0 ? true : false;
}

var debugId = false;	

function walert(s){	window.status = s; }

function malert(s){
	if (debugId==1) alert(s);
	if (debugId==2) walert(s);
}

function setDebugId(v){
	// 1 alert // 2 status bar
	walert("debugId ("+v+")");
	debugId=v;
}

function getId(id) {
	return $('#'+id);
}

var lastId = 0;	
function statId(id){
	if (debugId) alert("statId "+id);
	if (!checkId(id)) return;
	display = $(id).css('display');
	opacity = $(id).css('opacity');
	//firelog("statId "+id+" display "+display+" opacity "+opacity);
	if (display=="none" || opacity==0) return 0;
	else return 1;
}

function hideId(id){
	if (debugId) alert("hideId "+id);
	if (!checkId(id)) return;
	$('#'+id).hide();
}

function showId(id,mode){
	if (debugId) alert("showId "+id);
	if (!checkId(id)) return;
	var mode = (mode == null) ? 0 : mode;
	if (!mode) lastId = id;
	$('#'+id).show();
}

function toggleId(id,mode){
	if (debugId) malert("toggleId "+id);
	if (!checkId(id)) return;
	var mode = (mode == null) ? 0 : mode;
	if (!mode && lastId != id) hideId(lastId);
	$('#'+id).toggle();
}

function vislayer(){    
	this.lastId = '';
} 

vislayer.prototype.stat = function (id){
	if (!checkId(id)) return;
	opacity = $('#'+id).css('opacity');
	state   = $('#'+id).css('display');
	if (debugId) alert(id+" is display ["+state+"] opacity ["+opacity+"]");
	if (state=="block") return 1; else return 0;
}

vislayer.prototype.show = function (id,mode){
	if (debugId) malert("show "+id);
	if (!checkId(id)) return;
	var mode = (mode == null) ? 0 : mode;
	if (!mode) this.lastId = id;
	$('#'+id).show().css('opacity',1);
}

vislayer.prototype.hide = function (id){
	if (debugId) malert("hide "+id);
	if (!checkId(id)) return;
	$('#'+id).hide();
}

vislayer.prototype.toggle = function (id,mode){
	if (debugId) malert("toggle "+id);
	if (!checkId(id)) return;
	var mode = (mode == null) ? 0 : mode;
	if (!mode && this.lastId != id) this.hide(this.lastId);
	if (this.stat(id)) this.hide(id); else this.show(id,mode);
}

vislayer.prototype.slideDown = function (id,mode){
	if (debugId) malert("slideDown "+id);
	if (!checkId(id)) return;
	var mode = (mode == null) ? 0 : mode;
	if (!mode) this.lastId = id;
	$('#'+id).slideDown("slow").css('opacity',1);
}

vislayer.prototype.slideUp = function (id){
	if (debugId) malert("slideUp "+id);
	if (!checkId(id)) return;
	$('#'+id).slideUp("slow");
}

vislayer.prototype.slideUpDown = function (id,mode){
	if (debugId) malert("slideUpDown "+id);
	if (!checkId(id)) return;
	realthis = this;
	$('#'+this.lastId).slideUp("slow", function () { realthis.slideDown(id,mode); } );
}

vislayer.prototype.faderIn = function (id,mode){
	if (debugId) malert("fadeIn "+id);
	if (!checkId(id)) return;
	var mode = (mode == null) ? 0 : mode;
	if (!mode) this.lastId = id;
	alert("last "+this.lastId);
	$('#'+id).fadeIn().css('opacity',1);
}

vislayer.prototype.faderOut = function (id){
	if (debugId) malert("faderOut "+id+" busy "+this.busy);
	if (!checkId(id)) return;
	$('#'+id).fadeOut("slow", function () { this.busy = false; malert("faderOut "+id+" busy "+this.busy); } );
}

vislayer.prototype.faderInOut = function (id,mode){
	if (typeof(this.busy) == "undefined") this.busy = false;
	if (debugId) malert("faderInOut "+id+" busy "+this.busy);
	if (!checkId(id)) return;
	if (this.busy) return;
	realthis = this;
	previousId = this.lastId;
	if (previousId == id) $('#'+id).fadeIn("slow");
	else {
		this.busy = true;
		$('#'+id).fadeIn("slow", function () { realthis.faderOut(previousId,mode); walert("busy "+this.busy); } );
	}
	if (!mode) this.lastId = id;
}

vislayer.prototype.slideToggle = function (id,mode){
	if (debugId) malert("slideToggle "+id);
	if (!checkId(id)) return;
	var mode = (mode == null) ? 0 : mode;
	// a panel is open, and its not this one // close it first
	if (this.stat(this.lastId) && this.lastId != id) {
		this.slideUpDown(id,mode);
	} else {
		if (this.stat(id)) this.slideUp(id); else this.slideDown(id,mode);
	}
}
