var debugId = false;	

function w3c(ready){
	if (!ready) {
		setTimeout("w3c(1)",2000);
		return;
	}
	$('body').prepend("<div id='w3c' style='position:absolute;top:5px;left:5px'></div>");
	$('#w3c').load('/bin/w3c.php?url='+location.href);
}

function redirect_url(url){
	window.location=url;
}

function preload(_images,id){
	if (typeof(_image)=='undefined') return;
	var gotime = _images.length;
	if (!gotime) return;
	$('#busy').fadeIn();
	$.each(_images,function(e) {
		$(new Image()).load(function() {
			if (--gotime < 1) {
				$('#busy').hide();
				if (typeof(id) != 'undefined' ) $(id).fadeIn();
				window.status = '';
			} else {
				window.status = gotime + " remaining - "+this.src;
			}
		}).attr('src',this);
	});
}

var info_bubble_timeout = 0;
function info_bubble(bubble_class,txt){
	if (info_bubble_timeout) clearTimeout(info_bubble_timeout);
	if (!checkId("info_bubble")) alert("Cannot display info_bubble, please create #info_bubble");
	$('#info_bubble').addClass(bubble_class).html(txt);
	$('#info_bubble').slideDown().delay(5000).slideUp();
	info_bubble_timeout = setTimeout("info_bubble_timeout=0;$('#info_bubble').removeClass('"+bubble_class+"').html('');",7000);
}

function firelog(s){
	if (typeof(console)!="undefined") console.log(s);
}

function checkId(id){
	if (!id) return;
	id = id.replace("#","");
	if (!id) return;
	c = $('#'+id).length;
	//firelog("checkId "+id+" "+c);
	return (c > 0);
}

// stop ajax forms being submitted for invalid forms
function check_form(formData, jqForm, options){
	if (typeof(options.id)=='undefined') alert("Cannot check form, no id passed");
	id = options.id;
	if (!checkId(id)) alert("Cannot check form, id ["+id+"] does not exist.");
	if (options.cc_check) {
		$(id+' span.error').hide();
		// vars inside function not visible outside and return is local!
		var queryString = $(id).formSerialize();
		$.ajax({
		async : false, // this is ajax!!! waits for no man and check_form() can return before ajax sets state false!!
		url : '/bin/check_card.php', 
		data : queryString, 
		dataType : 'json',
		success : function(data) {
				state = data.result;
				if (!state) $(id+' span.error').html(data.messages).fadeIn(2500);
			}
		});
		if (state==true) {
			$(options.target).addClass('busy');
			$('.confirm_purchase').hide();
		}
		return state;
	} else {
		if ($(id).valid()) {
			$(options.target).addClass('busy');
			return true;
		} else {
			return false;
		}
	}
}

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'
	});
}

// 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 toggle_checkbox(id) {
	el = document.getElementById(id); 
	if (!el) {
		walert("Cannot set checkbox, no such id ["+id+"]");
		return;
	}
	el.value = 1-el.value;
}

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;
}

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 getURLParameter(name) {
    return unescape(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

function ajaxtarget(o,target){
	ajaxclass = $(o).attr('class').split(" ");
	for (var i=0, len=ajaxclass.length; i<len; ++i ){
		if (ajaxclass[i].match('target_')){
			target = "#"+ajaxclass[i].replace('target_','');
		}
	}
	return target;
}

function cartInit(redirect,is_cm){
	// cart
	if (getURLParameter('checkout')==1) loadFade('.ajax','/bin/cart_display.php?checkout=1');
	$(".go_login").live('click',function(){
                loadFade(ajaxtarget(this,'.ajax'),'/bin/cart_account.php?sleep=0');
        });
	$(".go_login_account").live('click',function(){
                loadFade(ajaxtarget(this,'.ajax'),'/bin/cart_account.php?sleep=0&redirect=/bin/account.php');
        });
	$(".go_logout").live('click',function(){
		loadFade(ajaxtarget(this,'.ajax'),'/bin/cart_account.php?logout_quietly=1');
	});
	$(".go_lost_password").live('click',function(){
		loadFade(ajaxtarget(this,'.ajax'),'/bin/lost_password.php?sleep=0');
	});
	$('.go_account').live('click',function() {
		loadFade(ajaxtarget(this,'.ajax'),'/bin/account.php');
	});
	$(".go_cart_account").live('click',function(){
                loadFade(ajaxtarget(this,'.ajax'),'/bin/cart_account.php');
        });
	$('.go_cart_change_other').live('click',function() {
		loadFade(ajaxtarget(this,'.ajax'),'/bin/cart_display.php?checkout=1&clear_other_address_set=1');
	});
	$('.go_cart_view').live('click',function() {
		loadFade(ajaxtarget(this,'.ajax'),'/bin/cart_display.php?checkout=0');
	});
	$('.go_cart_checkout').live('click',function() {
		loadFade(ajaxtarget(this,'.ajax'),'/bin/cart_display.php?checkout=1');
	});
	$('.go_cart_clear').live('click',function() {
		loadFade(ajaxtarget(this,'#cart_summary'),'/bin/cart_summary.php?clear_cart=1');
	});
	$('.go_cart_update').live('click',function() {
		refresh_cart();
	});
	$('.go_cart_delivery_address').live('click',function() {
		$('.account_delivery_address').slideToggle();
		$('.account_delivery_address input,.account_delivery_address select').toggleClass('required');
	});
	$('.go_cart_payment_method').live('change',function() {
		if (this.value=="use_new_card"){
			$('#new_card').fadeIn();
			$('#confirm_security_code').fadeOut();
		} else {
			$('#new_card').fadeOut();
			$('#confirm_security_code').fadeIn();
		}
	});
}

var loadFadeTimeout = 0;
function loadFade(id,url,in_dur,out_dur){
	if (typeof(in_dur)=='undefined')  in_dur  = 600;
	if (typeof(out_dur)=='undefined') out_dur = 0;
	if (loadFadeTimeout) clearTimeout(loadFadeTimeout);
	loadFadeTimeout = setTimeout("$('#loadFade').addClass('busy')",2500);
	$(id).wrap("<div id='loadFade'></div>");
	$(id).fadeOut(out_dur,function(){ 
		$(id).load(url,function(){ 
			cufon(1); 
			clearTimeout(loadFadeTimeout);
			$(id).unwrap().fadeIn(in_dur, function(){ $(id).removeClass('busy'); $('.fade_in').animate({ opacity: 1},600); });
		}); 
	});
}

function refresh_cart(){
	loadFade('.ajax','/bin/cart_display.php');
	$('#cart_summary').addClass('busy').load('/bin/cart_summary.php', function(){});
}

