var isIE=(navigator.appVersion.indexOf("MSIE")!=-1)?true:false;
var isWin=(navigator.appVersion.toLowerCase().indexOf("win")!=-1)?true:false;
var isOpera=(navigator.userAgent.indexOf("Opera")!=-1)?true:false;

// overlabel MT
( function($)
  {
  // plugin definition
  $.fn.overlabel = function( options ) {

  // build main options before element iteration
  var opts = $.extend( {}, $.fn.overlabel.defaults, options );

  var selection = this.filter( 'label[for]' ).map( function() {

	  var label = $( this );
	  var id = label.attr( 'for' );
	  var field = document.getElementById( id );

	  if ( !field ) return;

	  // build element specific options
	  var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;

	  label.addClass( o.label_class );

	  var hide_label = function() { label.css( o.hide_css ) };
	  var show_label = function() { this.value || label.css( o.show_css ) };

	  $( field )
	  .parent().addClass( o.wrapper_class ).end()
	  .focus( hide_label ).blur( show_label ).each( hide_label ).each( show_label );

	  return this;

  } );

  return opts.filter ? selection : selection.end();
  };

  // publicly accessible defaults
  $.fn.overlabel.defaults = {

label_class:   'overlabel-apply',
	wrapper_class: 'overlabel-wrapper',
	hide_css:      { 'text-indent': '-10000px' },
	show_css:      { 'text-indent': '0px', 'cursor': 'text' },
	filter:        false

  };

  } ) (jQuery);
//end overlabel

// reload captcha; can be removed; remember to remove it from the image too //
function reloadCaptcha()
{
	//document.getElementById('captcha').src = document.getElementById('captcha').src+ '?' +new Date();
	document.getElementById('captcha').src = document.getElementById('captcha').src.split('&')[0] + '&time=' + new Date().getTime();
}
function change_finished(){
	if ($("#unsucc").text() == "Finished Auctions")
	$("#unsucc").text("Unsuccessful Auctions");	
	else
	$("#unsucc").text("Finished Auctions");	
}
function change_finished_fr(){
	if ($("#unsucc").text() == "Enchères terminées")
	$("#unsucc").text("Enchères infructueuses");	
	else
	$("#unsucc").text("Enchères terminées");	
}
function my_alert(t){
	$("#dialog").text(t);
	$("#dialog").dialog("open")
}
function clear_alert() {
	$("#dialog").dialog("close");    
	$("#dialog").text('')
}

function set_main_image(C,A,B){
	$(".tlist a.image").removeClass("sel");
	$("#"+C).addClass("sel");
	$("#"+A).attr("src",B);return false
}

function hide_cat_list(A){
	cl=$("#catlist");
	cm=$("#catmenu");
	if((A.clientX<cl.offset().left+2)||(A.clientX>(cl.offset().left+cl.width()-4))||
			(A.clientY<cm.offset().top+2)||(A.clientY>(cl.offset().top+cl.height()-2)) ||
			((A.clientX<(cm.offset().left+10) && (A.clientY<cl.offset().top)))){
		cl.hide()
	}catlistmenu=false
}function show_cat_list(A){
	if(!catlistmenu){
		offset=$("#catmenu").offset();offset.top+=$("#catmenu").height();
		if($.browser.safari||$.browser.msie){
			offset.left--
		}
		$("#catlist").css(offset).slideDown(50);catlistmenu=true
	}
}
function hide_cat_home(A){
	cmh=$("#categories_main");
	ch=$("#catmenu_home");
	if(A.clientX<cmh.offset().left+2||A.clientX>(cmh.offset().left+cmh.width()-4)||
			A.clientY<ch.offset().top+2||A.clientY>(cmh.offset().top+cmh.height()-2)||
			((A.clientX>(ch.offset().left+ch.width())) && (A.clientY<cmh.offset().top)) ||
			((A.clientX<(ch.offset().left)) && (A.clientY<cmh.offset().top))){
		cmh.hide()
	}catlisthome=false
}
function show_cat_home(A){
	if(!catlisthome){
		offset=$("#catmenu_home").offset();offset.top+=$("#catmenu_home").height();
		if($.browser.safari||$.browser.msie){
			offset.left--
		}
		$("#categories_main").css(offset).slideDown(50);catlisthome=true
	}
}
function hide_last(A){
	var ll=$("#last_list");
	var lh=$("#last_header");
	if(A.clientX<ll.offset().left+2||A.clientX>(ll.offset().left+ll.width()-4)||
			A.clientY<lh.offset().top+2||A.clientY>(ll.offset().top+ll.height()-2)||
			((A.clientX<lh.offset().left+10) && (A.clientY<ll.offset().top)) || (A.clientX>lh.offset().left+lh.width()-4)){
		ll.hide(250);
	}
	lastlistmenu=false
}
var pos_x = 0;
var pos_y = 0;
var c = 0;
var delay;
var timer_is_on=0;

function doTimerLast()
{
	if (!timer_is_on)
	{
		timer_is_on=1;
		clearTimeout(delay);
		timedCountLast();
	}
}
function timedCountLast() {        
	show_last();
	c=c+1;

	$("#num").text(c);
	if (c >= 6) {
		c = 0;
		timer_is_on=0;
		//      pos_last();
		$("#num").text(c);
		clearTimeout(delay);
		return;	
	}
	delay=setTimeout("timedCountLast()",50);

}
function positionLast(A) {
	//if (!A) var A = window.event;
	var A=(!A)?window.event:A;
	if (A.pageX || A.pageY) {
		pos_x = A.pageX;
		pos_y = A.pageY;
	}
	else if (A.clientX || A.clientY) { //IE, FF
		pos_x = A.clientX;
		pos_y = A.clientY;
	}
	$("#position").text(c +" " + delay +" posx=" + pos_x +" head_left=" + $("#last_header").offset().left);
	pos_last();
}

function pos_last() {
	positionLast(event);
	var head = $("#last_header");
	$("#position").text(c +" " + delay +" posx=" + pos_x +" head_left=" + $("#last_header").offset().left);
	//	var diff = setTimeout("position(event)",200); 
	//     pause(200).position(A)
	if((pos_x>=head.offset().left) && (pos_x<=(head.offset().left+head.width())) && 
			(pos_y>=head.offset().top) && (pos_y<=(head.offset().top+head.height())))
	{
		show_last();
		//	  c = 0;
		//        timer_is_on=0;
		//          clearTimeout(delay);
	}        	 	          
}
function show_last(){
	//	$("#position").text(A + " posx=" + pos_x +" head_left=" + $("#last_header").offset().left);
	var ll = $("#last_list");
	var head = $("#last_header");
	if(!lastlistmenu){   
		var offset=head.offset();
		offset.top+=head.height();
		if($.browser.safari||$.browser.msie){
			offset.left--
		}
		ll.css(offset).slideDown(700);
		lastlistmenu=true;
	}
}
/*setTimeout(function(){
// A bunch of code   setInterval(
// Something...
// Even more
},1000);*/
var GAL;var GALD;var GALP;var GAF;
var STATLCK=false;var STATSRV="";
var catlistmenu=false;
var lastlistmenu=false;
var catlisthome=false;
var sw=false;var lock_count=0;

function show_det_bids(){
	$("#hhead").removeClass("sec");
	$("#detbl1").show();
	$("#detbl2").hide();return false
}
function show_det_ab(A){
	$("#hhead").addClass("sec");
	$("#detbl2").show();
	$("#detbl1").hide();
	$("#l2").removeClass("sel");
	$("#l1").addClass("sel");
	$("#f1a").hide();$("#f1b").show();return false
}

$(document).ready(function() {         //pause function
		$.fn.pause = function(duration) { 
		$(this).animate({ dummy: 1 }, duration); 
		return this; 
		}; 
		}); 

$(document).ready(function(){

		$("#form_buttons").css("display", "block"); //MT

		$("#dialog").dialog({
autoOpen:false,
modal:true,
height:170, // MT
// width:300,
buttons:{
OK:function(){
$(this).dialog("close")
}
},
show:'slide',
hide: 'slide',
zIndex: 3999,
overlay:{
opacity:0.3
}
});

if($.browser.msie){
	$("input").focus(function(){
			$(this).addClass("focused")
			}).blur(function(){
				$(this).removeClass("focused")
				}).hover(function(){
					$(this).addClass("hovered")
					},function(){
					$(this).removeClass("hovered")
					})
}
//$("#mainImage").pause(5000).fadeOut(); 
$("label.overlabel").overlabel();
$("#catmenu").click(show_cat_list);
$("#catmenu").mouseout(hide_cat_list);
$("#catlist").mouseout(hide_cat_list);
//$("#catlist").mouseleave(hide_cat_list);
$("#catmenu_home").click(show_cat_home);
$("#catmenu_home").mouseout(hide_cat_home);
$("#categories_main").mouseout(hide_cat_home);

$("#last_header").click(doTimerLast);
$("#last_header").mouseout(hide_last);
$("#last_list").mouseout(hide_last);
//    $("#last_list").mouseleave(hide_last);
$(".auction .loupe").click(function(){
		tb_show("http://www.spaceantiques.ca/en/auction/gallery/"+/#zoom-(\d+)/.exec(this.href)[1]);return false
		})
$(".auction .loupe_pic").click(function(){
		tb_show("http://www.spaceantiques.ca/org.LuckyBids.ca/winners/"+/#pic-(\d+)/.exec(this.href)[1]);return false
		})
$(".auction .image_w").click(function(){
		tb_show("http://www.spaceantiques.ca/org.LuckyBids.ca/winners/"+/#pic-(\d+)/.exec(this.href)[1]);return false
		})
$('#phone1').autotab({ target: 'phone2', format: 'numeric', nospace: true });
$('#phone2').autotab({ target: 'phone3', format: 'numeric', previous: 'phone1', nospace: true });
$('#phone3').autotab({ previous: 'phone2', format: 'numeric', nospace: true });
/*$('#postal_code1').autotab({ target: 'postal_code2', format: 'alphanumeric', uppercase: true, nospace: true});
  $('#postal_code2').autotab({ previous: 'postal_code1', format: 'alphanumeric', uppercase: true, nospace: true });
  $('#s_postal_code1').autotab({ target: 's_postal_code2', format: 'alphanumeric', uppercase: true, nospace: true });
  $('#s_postal_code2').autotab({ previous: 's_postal_code1', format: 'alphanumeric', uppercase: true, nospace: true });*/

/*************************/
//integer number format
$("#bids_rew").keydown(function (event) {
    // Prevent shift key since its not needed
    if (event.shiftKey == true) {
        event.preventDefault();
    }
    // Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
        // Allow normal operation
    } else {
        // Prevent the rest
        event.preventDefault();
    }
});

/***************************/
//Register validation functions - MT
/***************************/

//global vars
var form = $("#registration_form");
var checkbox = $("#checkbox");
var username = $("#username");
var usernameInfo = $("#usernameInfo");
var first_name = $("#first_name");
var first_nameInfo = $("#first_nameInfo");
var last_name = $("#last_name");
var last_nameInfo = $("#last_nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var promo_code = $("#promo_code");
var promo_codeInfo = $("#promo_codeInfo");
//var emailc = $("#emailc");
//var emailConfirm = $("#emailConfirm");
var password1 = $("#password1");
var password1Info = $("#password1Info");
var password2 = $("#password2");
var password2Info = $("#password2Info");
//var street1 = $("#street1");
//var street1Info = $("#street1Info");
//var city = $("#city");
//var cityInfo = $("#cityInfo");
var province = $("#province");
var provinceInfo = $("#provinceInfo");
var state = $("#state");
var secure = $("#secure");
var secureInfo = $("#secureInfo");
//On change
province.change(validateProvince);
state.change(validateProvince);
//On blur
//username.blur(validateUsername);
username.blur(check_users);
//email.blur(validateEmail);
email.blur(check_email);
promo_code.blur(check_promo_code);
secure.blur(check_captcha);
password1.blur(validatePassword1);
password2.blur(validatePassword2);
first_name.blur(validateFirst_name);
last_name.blur(validateLast_name);
//On key press
username.keyup(validateUsername);
email.keyup(validateEmail);
password1.keyup(validatePassword1);
password2.keyup(validatePassword2);
first_name.keyup(validateFirst_name);
last_name.keyup(validateLast_name);
secure.keyup(validateCaptcha);
var var_check_users = false;
var var_check_email = false;
var var_check_promo = false;
var var_check_captcha = false;

//On Submitting 
	form.submit(function() {
			if(var_check_users & validateUsername() & validateEmail() & var_check_email & validateFirst_name() & validateLast_name()  
				& validatePassword1() & var_check_captcha & validateCaptcha() & validatePassword2() & validateApprove() & validateProvince())
			{		
			return true;
			}
			else {
			return false;
			}
			});
//validate checkbox tc & ap
function validateApprove(){
	if (($("#approve_tc").attr("checked")) & ($("#approve_privacy").attr("checked")))
	{
		checkbox.removeClass("error");
		checkbox.text(" ");
		return true;
	}
	else
	{
		checkbox.addClass("error");
		checkbox.text(gettext("Approval of Terms and Conditions along with Privacy Policy is required"));
		return false;
	}
}
//validation e-mail
function validateEmail(){
	//testing regular expression
	var a = $("#email").val();
	var filter = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/; //usa
	//canada old	var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
	//    var filter =/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/;
	//if it's valid email
	if(filter.test(a)){
		email.removeClass("error_i");
		emailInfo.text(gettext("Enter E-mail please, you'll need it to confirm registration"));
		emailInfo.removeClass("error");
		return true;			
	}
	//if it's NOT valid
	else{
		email.removeClass().addClass("error_i");
		emailInfo.text(gettext("Enter a valid e-mail, please"));
		emailInfo.removeClass().addClass("error");
		return false;
	}
}
	function check_email(){
		if (!validateEmail())
			var_check_email = false;
		else {			
			emailInfo.removeClass().addClass("green").text(gettext('Checking...')).fadeIn("slow");
			// Ajax call to run the check  
			$.post("check_email.php", { e_mail:$("#email").val() },  
					function(result){
					var t1 = $("#email").val();
					var t2 = (gettext("You will receive confirmation e-mail on "));
					var t3 = (gettext(" already exists, choose another one"));
					//if the result is 1  
					if(result == 1){  
					//show that the username is available
					$("#email").removeClass("error_i");
					$("#emailInfo").text(t2 + "'" +t1+ "'");
					var_check_email = true;
					}
					else {  
					//show that the username is NOT available
					$("#email").addClass("error_i");
					$("#emailInfo").removeClass().addClass("error");
					$("#emailInfo").text("'" +t1+ "'" + t3);
					var_check_email = false;
					} 
					}); 
		}

	}
//username validation
function validateUsername(){
	var a = $("#username").val();
	var filter = /^[a-zA-Z0-9][a-zA-Z0-9_]*[a-zA-Z0-9]$/

		if($("#username").val().length < 4){    //if less than 4 char
			$("#username").addClass("error_i");
			usernameInfo.text(gettext("Username with at least 4 characters"));
			usernameInfo.removeClass().addClass("error");
			return false;
		}
		else if (!filter.test(a)) {         // if not alphanumeric
			$("#username").addClass("error_i");
			usernameInfo.text(gettext("Letters and Numbers only (or underscore(_) within)"));
			usernameInfo.removeClass().addClass("error");
			return false;
		}
	//if it's valid
		else {
			$("#username").removeClass("error_i");
			usernameInfo.removeClass("error");
			//usernameInfo.text(gettext("Choose your username: alphanumeric characters only")); 
			return true;
		}
}
//checking username availability
	function check_users(){
		if (!validateUsername())
			var_check_users = false;
		else {
			usernameInfo.removeClass().addClass("green").text(gettext('Checking...')).fadeIn("slow");
			// Ajax call to run the check  
			$.post("check_username.php", { user_name:$("#username").val() },  
					function(result){
					var t1 = $("#username").val();
					var t2 = (gettext(" is available"));
					var t3 = (gettext(" already exists, choose again"));
					//if the result is 1  
					if(result == 1){  
					//show that the username is available
					$("#username").removeClass("error_i");
					$("#usernameInfo").text("'" +t1+ "'" + t2);
					var_check_users = true;
					}
					else {  
					//show that the username is NOT available
					$("#username").addClass("error_i");
					$("#usernameInfo").removeClass().addClass("error");
					$("#usernameInfo").text("'" +t1+ "'" + t3);
					var_check_users = false;
					} 
					});
		}

	}
function check_promo_code(){
	if ($("#promo_code").val() != "") {
		promo_codeInfo.removeClass().addClass("green").text(gettext('Checking...')).fadeIn("slow");
		// Ajax call to run the check  
		$.post("check_promo_code.php", { promocode:$("#promo_code").val() },
				function(result){
				var t1 = $("#promo_code").val();
				var t2 = (gettext("You'll get a bonus when purchasing bids"));
				var t3 = (gettext(" is not a valid code or it is expired"));
				if(result != 0){ 	
				if (result = 1) {
				$("#promo_code").removeClass("error_i");
				$("#promo_codeInfo").text(t2);
				var_check_promo = true;
				}
				else {
				$("#promo_code").removeClass("error_i");
				$("#promo_codeInfo").text("different promo option");	
				}
				}
				else {  
				//show that the promo is NOT available
				$("#promo_code").addClass("error_i");
				$("#promo_codeInfo").removeClass().addClass("error");
				$("#promo_codeInfo").text("'" +t1+ "'" + t3);
				var_check_promo = false;
				} 
				});
	}
	else {
		$("#promo_code").removeClass("error_i");
		$("#promo_codeInfo").removeClass("error");
		$("#promo_codeInfo").text("If you have a valid promotion code enter it here");
		var_check_promo = true;	
	}

}

function validateCaptcha() {
	if($("#secure").val().length != 0){
		secureInfo.removeClass()
			return true;
	}
	else {
		secureInfo.removeClass().addClass("error");
		secureInfo.text(gettext("Wrong answer"));
		return false;
	}
}

function check_captcha() {
	if (!validateUsername())
		var_check_captcha = false;
	else {
		if ($("#secure").val() != "") {
			secureInfo.removeClass().addClass("green").text(gettext('Checking...')).fadeIn("slow");
			// Ajax call to run the check  
			//$.post("check_captcha.php", { captcha:$("#secure").val() },  
			$.post("check_captcha.php", { captcha:$("#secure").val(), session_id:sessionId },  
					function(result){
					var t2 = (gettext("OK"));
					var t3 = (gettext("Wrong answer"));
					if(result == 1){  
					//show that the captcha is ok
					secureInfo.text(t2);
					var_check_captcha = true;
					}
					else {  
					//show that captcha is wrong
					secureInfo.removeClass().addClass("error");
					secureInfo.text(t3);
					var_check_captcha = false;
					} 

					});
		}
		else {
			secureInfo.removeClass().addClass("error");
			secureInfo.text((gettext("Wrong answer")));
			var_check_captcha = false;	
		}
	}
}

function validatePassword1(){
	var a = $("#password1");
	var b = $("#password2");

	//it's NOT valid
	if(password1.val().length <5){
		password1.addClass("error_i");
		password1Info.text(gettext("Enter at least 5 characters"));
		password1Info.addClass("error");
		return false;
	}
	//it's valid
	else{
		password1.removeClass("error_i");
		password1Info.text(gettext("Choose and remember your password"));
		password1Info.removeClass("error");
		validatePassword2();
		return true;
	}
}
function validatePassword2(){
	var a = $("#password1");
	var b = $("#password2");
	//are NOT valid
	if( password1.val() != password2.val() ){
		password2.addClass("error_i");
		password2Info.text(gettext("Match the password, please"));
		password2Info.addClass("error");
		return false;
	}
	//are valid
	else{
		password2.removeClass("error_i");
		password2Info.text(gettext("OK"));
		password2Info.removeClass("error");
		return true;
	}
}
function validateFirst_name(){
	//it's NOT valid
	if(first_name.val().length < 1){
		first_name.addClass("error_i");
		first_nameInfo.addClass("error");
		first_nameInfo.text(gettext("Your name is required"));
		return false;
	}
	//it's valid
	else{
		first_name.removeClass("error_i");
		first_nameInfo.text(" ");
		first_nameInfo.removeClass("error");
		return true;
	}
}
function validateLast_name(){
	//it's NOT valid
	if(last_name.val().length < 1){
		last_name.addClass("error_i");
		last_nameInfo.addClass("error");
		last_nameInfo.text(gettext("Your last name is required"));
		return false;
	}
	//it's valid
	else{
		last_name.removeClass("error_i");
		last_nameInfo.text(" ");
		last_nameInfo.removeClass("error");
		return true;
	}
}
function validateProvince(){
	//var state = $("#state :selected").text();
	var st =  $("#state").val();
	var pr = $("#province").val();
	//var co = $("#country").val();
	if (!(st) & !(pr))
	{
		$("#province").addClass("error_i");
		$("#state").addClass("error_i");
		provinceInfo.addClass("error");
		provinceInfo.text(gettext("required"));
		st="";pr="";
		return false;
	}
	else
	{
		$("#province").removeClass("error_i");
		$("#state").removeClass("error_i");
		provinceInfo.text(" ");
		provinceInfo.removeClass("error");
		st="";pr="";
		return true;
	}

}

/****************************/
// refer friend e-mail validation MT
/****************************/
var form_inv = $("#invite");
var e_address = $("#e_address");
var e_Info = $("#e_Info");
e_address.change(validE_refer);
e_address.blur(validE_refer);
e_address.keyup(validE_refer);
//On Submitting 
	form_inv.submit(function() {
			if(validE_refer())
			{		
			return true;
			}
			else {
			return false;
			}
			});
//validation e-mail
function validE_refer(){
	//testing regular expression
	var e = $("#e_address").val();
	var filter1 = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/; 
	//if it's valid email
	if(filter1.test(e)){
		e_Info.text(gettext("(Enter your friend's email address)"));
		e_Info.removeClass("error");
		return true;			
	}
	//if it's NOT valid
	else{
		e_Info.text(gettext("Enter a valid e-mail, please"));
		e_Info.removeClass().addClass("error");
		return false;
	}
}
/*****************************/
//referal promo_buy code check MT
/*****************************/
var promo_buy = $("#promo_buy");
var promo_buyInfo = $("#promo_buyInfo");
promo_buy.blur(check_promo_buy);
//var bids_percent;
var discount_percent;

function check_promo_buy() {
	// A promo code is entered, modify accordingly
	// array from ajax: policy, user_id_target, discount_percent, bids_percent
	if ($("#promo_buy").val() != "") {
		promo_buyInfo.removeClass().addClass("green").text(gettext('Checking...')).fadeIn("slow");
		// Ajax call to run the check 
		$.post("check_promo_buy.php", { promobuy:$("#promo_buy").val() },
				function(result) {
				var response = result.split(',');
				var t0 = $("#promo_buy").val();
				var t1 = (gettext("You'll get "+bids_percent+ "% more bids"));
				var t2 = (gettext("You have "+response[2]+"% discount"));
				var t3 = (gettext("Extra 25 bids with 25 Bids Pack only"));
				var tn = (gettext(" is not a valid code or it is expired"));
				if (parseInt(response[0]) != 0) { 

				if ((parseInt(response[0]) == 1)&&(parseInt(response[1]) == parseInt(user_id_target))) {	//POLICY 	     	   
				$("#promo_buy").removeClass("error_i");
				$("#promo_buyInfo").text(t1);
				bids_percent = parseInt(bids_percent)/100+1;
				discount_percent = 1;
				changeTotal();
				setItemNumber(true);

				}
				else if (parseInt(response[0]) == 2) {
				$("#promo_buy").removeClass("error_i");
				$("#promo_buyInfo").text(t2);
				bids_percent = 1;
				discount_percent = 1 - parseInt(response[2])/100;
				changeTotal();
				setItemNumber(true);
				}
						else if (parseInt(response[0]) == 3) {
						$("#promo_buy").removeClass("error_i");
						$("#promo_buyInfo").text(t3);
						setItemNumber(true);
					}
				else if (parseInt(response[0]) > 3) {
					$("#promo_buy").addClass("error_i");
					$("#promo_buyInfo").removeClass().addClass("error");
					$("#promo_buyInfo").text(t0 + "code doesn't apply here");
					bids_percent = 1;
					discount_percent = 1;
					changeTotal();
					setItemNumber(false);
				}
				else {
					$("#promo_buy").addClass("error_i");
					$("#promo_buyInfo").removeClass().addClass("error");
					$("#promo_buyInfo").text("'" +t0+ "'" + tn);
					changeTotal();
					setItemNumber(false);
				}
				}
				else {  
					//show that the promo is NOT available
					$("#promo_buy").addClass("error_i");
					$("#promo_buyInfo").removeClass().addClass("error");
					$("#promo_buyInfo").text("'" +t0+ "'" + tn);
					bids_percent = 1;
					discount_percent = 1;
					changeTotal();
					setItemNumber(false);
				}

				});
	}
	// No promotion code is entered, reset the whole thing
	else {
		$("#promo_buy").removeClass("error_i");
		$("#promo_buyInfo").removeClass();
		$("#promo_buyInfo").text("If you have a valid promotion code enter it here");
		bids_percent = 1;
		changeTotal();
		setItemNumber(false);
		var_promo_buy = true;	
	}
}	

/* ==========================================================
   On Country Change -- Mike
   ========================================================== */

$('#country').change(function(){
		if($('#country').val() == 'USA'){		
		$('#country_2').html('U S A');
		$("label[for='id_ship_state']").html('State');
		$("label[for='province']").html('State');

		$('#state').show();	
		$('#province').hide();

		$('#province').attr('name','province_unused');	
		$('#state').attr('name','province');					

		$('#id_state_secondary').show();	
		$('#id_state1').hide();

		$('#id_state_secondary').attr('name','ship_province');	
		$('#id_state1').attr('name','ship_province_unused');			

		$("label[for='postal_code']").html('Zip Code');
		$("label[for='id_s_postal_code']").html('Zip Code');

		$('#postal_code1').attr('maxlength','5');	
		$('#postal_code2').attr('maxlength','4');

		$('#s_postal_code1').attr('maxlength','5');	
		$('#s_postal_code2').attr('maxlength','4');

		$('.us_dash').html('-');

		$('#whatIsCountry').attr('name','us');
		}	
		if($('#country').val() == 'Canada'){		
			$('#country_2').html('Canada');
			$("label[for='id_ship_state']").html('Province');
			$("label[for='province']").html('Province');			

			$('#state').hide();	
			$('#province').show();

			$('#state').attr('name','province_unused');	
			$('#province').attr('name','province');					

			$('#id_state_secondary').hide();	
			$('#id_state1').show();

			$('#id_state1').attr('name','ship_province');	
			$('#id_state_secondary').attr('name','ship_province_unused');

			$("label[for='postal_code']").html('Postal Code');
			$("label[for='id_s_postal_code']").html('Postal Code');

			$('#postal_code1').attr('maxlength','3');	
			$('#postal_code2').attr('maxlength','3');

			$('#s_postal_code1').attr('maxlength','3');	
			$('#s_postal_code2').attr('maxlength','3');						

			$('.us_dash').html('');

			$('#whatIsCountry').attr('name','ca');
		}	
});



/****************************************************************/
// Calculation of totals for PayPal order summary   //MT
/****************************************************************/   	
//global vars

var price = $("#price_voucher");
var priceVoucher = (parseFloat(price.val())).toFixed(2);
$("#price").text('$ ' + priceVoucher);

var hst = $("#hst");
if (hst.text())
{	
	var hstArray = (hst.text()).split(" ");
	var hstCal = (parseFloat(hstArray[1])).toFixed(2);
	hst.text('$ ' + hstCal);
}
else
{  
	var gst = $("#gst");
	var gstArray = (gst.text()).split(" ");
	var gstCal = (parseFloat(gstArray[1])).toFixed(2);
	gst.text('$ ' + gstCal);
}
var qst = $("#qst");
if (qst.text()) 
{
	var qstArray = (qst.text()).split(" ");
	var qstCal = (parseFloat(qstArray[1])).toFixed(2);
	qst.text('$ ' + qstCal);
}	
var total = $("#total");
var totalArray = (total.text()).split(" ");
var totalCal = (parseFloat(totalArray[1])).toFixed(2);
total.text('$ ' + totalCal);

//On change
//quantity.change(changeTotal);

function changeTotal() {

	$("#bids_amount").text(Math.ceil(parseInt($("#bids_voucher").val()) * bids_percent));
	$('input[name="item_name"]').val(Math.ceil(parseInt($("#bids_voucher").val()) * bids_percent)+ " Bids Pack");
	// item_number must _not_ be changed here
	//$('input[name="item_number"]').val("b" + Math.ceil(parseInt($("#bids_voucher").val()) * bids_percent));

	var priceCal = (parseFloat(priceVoucher) * discount_percent).toFixed(2);
	$("#price").text('$ ' + priceCal);

	if (hst.text()) {
		var hst_rateArray = ($("#hst_rate").text()).split("%");
		var hst_rate = parseInt(hst_rateArray[0]);
		hstCal = (parseFloat(priceCal) * (hst_rate/100).toFixed(2)).toFixed(2);
		hst.text('$ ' + hstCal);
		var gstCal = 0;
	}
	else {
		gstCal = (parseFloat(priceCal) * .05).toFixed(2);
		gst.text('$ ' + gstCal);
		var hstCal = 0;
	}
	if (qst.text()) {
		qstCal = (((parseFloat(priceCal) + parseFloat(gstCal)) * .085)).toFixed(2);
		qst.text('$ ' + qstCal);
	}
	else {
		var qstCal = 0;
	}   
	var totalCal = parseFloat(priceCal) + parseFloat(gstCal) + parseFloat(qstCal) + parseFloat(hstCal);
	total.text('$ ' + totalCal.toFixed(2));
	$('input[name="amount"]').val(totalCal.toFixed(2));
}

// Following any action on promo_buy field, set item_number
function setItemNumber(change) {
	var a = $("[name='item_number']").attr("value");
	a = a.split('p');

	if (change == true)
		a = a + 'p' + $("#promo_buy").val();
	else
		a = a[0];

	$("[name='item_number']").attr("value", a);
}

//});	


$(".dropdown dt a").click(function() {
		$(".dropdown dd ul").toggle();
		});

$(".dropdown dd ul li a").click(function() {
		var text = $(this).html();
		$(".dropdown dt a span").html(text);
		$(".dropdown dd ul").hide();

		if($(this).find("span.value").html() == "USA"){
		window.location = "http://spaceantiques.com/";	
		}

		if($(this).find("span.value").html() == "CAN"){
		window.location = "http://spaceantiques.ca/";	
		}

		});

$(document).bind('click', function(e) {
		var $clicked = $(e.target);
		if (! $clicked.parents().hasClass("dropdown"))
		$(".dropdown dd ul").hide();
		});

window.setTimeout(setDropDown, 400);

function setDropDown(){
	if(window.location.host == "spaceantiques.com" || window.location.host == "www.spaceantiques.com"){			
		$("#dropdown dt a span").html('United States<img class="flag can" src="http://spaceantiques.ca/org.LuckyBids.ca/images/usa.png" alt="" />');				
	} else {
		$("#dropdown dt a span").html('Canada<img class="flag" src="http://spaceantiques.ca/org.LuckyBids.ca/images/can.png" alt="" />');	
	}
}		
});

/* === BEGIN JS COOKIE SCRIPT === */
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}	
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
/* === END JS COOKIE SCRIPT === */	

function spacebidder_main(){			
	var spacebid = getCookie('spacebid');	
	if (spacebid != 1 || spacebid != "1") {	
		setCookie('spacebid',1,99);

		var caution1 = gettext("Your SpaceBidder can place a large number of bids in a split second. ");
		var caution2 = gettext("See SpaceBidder in Help section for more details.");
		var spaceBidderAlert = caution1 + caution2;	
		var proceed_txt = gettext("Proceed");
		var cancel_txt = gettext("Cancel");

		var buttonsOpts = {};
		buttonsOpts[cancel_txt] = function(){$(this).dialog("close");};
		buttonsOpts[proceed_txt] = function(){document.set_autobid.submit();$(this).dialog("close");};

		$(function(){

				$("#spacebid_dialog").html(spaceBidderAlert);
				$("#spacebid_dialog").dialog({	
autoOpen: false,
modal:true,
buttons:buttonsOpts,
show:'slide',
hide: 'slide',
zIndex: 3999,
overlay:{
opacity:0.3
}							
});	
				$("#spacebid_dialog").dialog("open"); 	

				});
} else {
	document.set_autobid.submit();	
}
return false;
}

