//Various Variables
var initialized = false;

var regionInit = false;

//-Below are all Collected from form;
var current_step = 0; 

var baseCost = 0; 

var maxImages = 0; 
var freePics = 0; 
var images = 0;


//Keep Track of The image inputs
var imageRows = new Array(maxImages);
var imageRecall = 0;
var send_pics_method = '';

var totalLoc = new Array();
var lastScroll = 0;
var scrollInit = false;

//Showing the AJAX Image Uplaoder?
var imageShow = true;
var ImageClick = false;

//Debug:document.getElementById('debug').innerHTML =
var uploadDebug = true;

var uploadsp = '';

//Fire up the script
$(window).ready(function(){
	//If the the form is not an object, don't do anything
	if (document.getElementById('listingForm') == null) {
		HelpText();
		return;
	}
	
	//Let the form processor know we'ew up to AJAX
	document.getElementById('listingForm').innerHTML += '<input type="hidden" name="ajax" value="true" />';
	
	//Disable Enter keys
	$('input').bind('keypress',function(e) {
		if (disableEnterKey(e)) return true;
		
		//Grab the parent form
		var form = this.form;
		
		//Tab forward if we can
		var tabIndex = this.tabIndex;
		var next = -1;
		var tabTo = -1;
		for (var i=0; i < form.elements.length; i++) {
			var thisTabIndex = form.elements[i].tabIndex;
			var id = $(form.elements[i]).attr("id");
			//if (!confirm(i+'|id:'+id+'|tab:'+thisTabIndex)) break;
			if (thisTabIndex == 0 || id == undefined || id == '') continue;
			var parentId = $('#'+id).closest("tr").attr('id');
			if (parentId == undefined || parentId == '') continue;
			//alert(tabIndex+'|thisTabIndex:'+thisTabIndex+'|next:'+next+'|display:'+$('#'+ parentId).css('display'));
			
			if ($('#'+parentId).css('display') == "none") continue;
			
			if (thisTabIndex > tabIndex && (next == -1 || thisTabIndex < next)) {
				next = thisTabIndex;
				tabTo = i;
			}
		}
		if (tabTo != -1) {
			form.elements[tabTo].focus();
		}
		
		return false;
		
	});
	
	
	//Init the Region
	AutoRegion();
	
	//Init The calculator
	//Debug:alert("["+ document.getElementById('Total') +"]");
	if (document.getElementById('Total') != null) {
		TotalMover();
		//debug:alert("["+ document.getElementById('Total') +"]");
		AutoCalculate();
	}
	
	//Bind Image Map Swapper
	if (document.getElementById('canMap') != null) {
		$('#canMap > area').click(function () {
			var region = $(this).attr('href').match(/[^\/\.]+/gi);
			//debug:alert("Cool"+ region[1]);
			$('#First_list_region > option').each(function() {
				$(this).removeAttr("selected");
			});
			$('#list_region_'+ region[1]).attr("selected", "selected");
			clickRegion();
			return false;
		});
		$('.h_back').click(function() {
			$('#First_list_region > option').each(function() {
				$(this).removeAttr("selected");
			});
			$('#list_region_').attr("selected", "selected");
			clickRegion();
			return false;
		});
	}
	
	HelpText();
	
});
//-TotalMover
function TotalMover() {
	$(document).scroll(function() {
		if (!scrollInit) {
		lastScroll = $(document).scrollTop();
		totalLoc = $('#TotalBox').offset();
		
		/*$('#debug').append('<br />('+ lastScroll +')('+$(document).scrollTop()+')('+ totalLoc.top+')<div id="newloc"></div>');
		$('#debug').css('position', 'fixed');
		$('#debug').css('bottom', '0');
		$('#debug').css('width', '100%');
		$('#debug').css('background-color', 'white');
		$('#debug').show()
		$('#debug').append('<br />('+ lastScroll +')('+ totalLoc.top+')');*/
		$
		('#TotalBox').css('z-index', '999');
		scrollInit = true;
	}
	

	var s = $(document).scrollTop();
	//$('#newloc').html('('+ s +')('+ totalLoc.top+')');
		if (s > totalLoc.top) {
			$('#TotalBox').stop();
			$('#TotalBox').css('position', 'fixed');
			$('#TotalBox').css('top', '0');
		} else {
			$('#TotalBox').stop();
			
			$('#TotalBox').css('position', '');
			$('#TotalBox').css('top', '');
		}
	});
}


//--Enter Keys---//

function disableEnterKey(e) {
	var key;     
	if(window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //firefox     

	return (key != 13);
}




//---------------------------- Calculator ----------------------------//
function AutoCalculate() {
	//Check for all elements - Exit if not found
	if (document.getElementById('calculate') != null) {
		//$("#imgerror").append("Loading SP...");
		uploadsp = $("input[name='uploadSP']").val();
		//Hide Calc Button
		$('#calculate').hide();
			
		//Fetch base cost
		baseCost = parseFloat($('#Total').html());
		
		//Fetch # of free pictures
		freePics = parseFloat($('#num_pics_meta_min').attr("value"));
		
		//Fetch max num of pics
		maxImages = parseFloat($('#num_pics_meta_max').attr("value"));

		//Init the Images
		initImages();
		imageRecall = images;
		
		//Check the radio button
		RadioChange();
		if (document.getElementById('Text_enable_text') != null) {
			TextMessaging();
			TextMessagingCost();
		}
		
		$('#TotalBox').show();
		
		//Bind Events
		$('.send_pics_radio').click(RadioChange);
		$('.text_amount_radio').click(TextMessagingCost);
		$('#Text_enable_text').click(TextMessaging);
		
		$('.number').keyup(Tally);
		$('.checkbox').click(Tally);
		
		initialized = true;
		//------
		
		uploadprefix = $("#prefix").val();
		if (!uploadsp) {
			//if (uploadDebug)$("#imgerror").append("Failed to load image handler. SP not found.");
			return;
		}
		//-Attach AjAx Image Handler to each imgFile
		//if (uploadDebug)$("#imgerror").append("SP="+ uploadsp);
		$(".imgFile").each(function() {
			var id = $(this).attr('id');
			//if (uploadDebug)$("#imgerror").append("<br />Bindingchanger["+ id +"]");
			$("#"+ id).change(changeBind);
			$("#delete"+ id).click(function() {
				clearImg(id);
			});

		});
		//-Bind Submit button to check for Queue
		$("input[name='submit']").each(function() {
			$(this).click(function() {
				//if (uploadDebug)$("#imgerror").append("<br />Submit Bound");
				if (upQueue.length) {
				/*	var ok = confirm("Images are still uploading.\nPress OK to wait or Cancel to Submit anyways.");
					return !ok;
				*/	alert("Images are still uploading. Please Wait.");
					return false;
				} else return true;
			});
		});
		
		//if (uploadDebug)$("#imgerror").append("<br />Change Bound");
		
		$("#listingForm").show();
		$("#FormLoad").hide();
		//----
	}
}
//----------------- Image Sending OPtion Radio ----------------
function RadioChange() {
	var send_pics = document.getElementsByName('send_pics');
	send_pics_method = send_pics[0].value;
	for (var i=0; i < send_pics.length; i++) {
		if (send_pics[i].checked) send_pics_method = send_pics[i].value;
	}
  //--LandMail: Hide Images, show number
	if (send_pics_method == "LMAIL") { //(send_pics[1].checked) {
		$('#num_pics_tr').show();
		HideImages();
		images = imageRecall;
		$('#ImageOptions_num_pics').attr("value", images);
	} else {
		//Otherwise Hide number
		$('#num_pics_tr').hide();
	}
  //None: Hold the image number, hide number of image, images and gallery
	if (send_pics_method == "NONE") { //(send_pics.length > 2 && send_pics[2].checked) {
		imageRecall = images;
		HideImages();
		images = 0;
		$('#ImageOptions_num_pics').attr("value", images);
		
		$('#ImageOptions_image_gallery').attr("checked", "");
		$('#image_gallery_tr').hide();

	} else {
		//Otherwise Show Gallery
		$('#image_gallery_tr').show();
	}
  //Electronic: Show the Images
	if (send_pics_method == "electronic") {
		images = imageRecall;
		$('#ImageOptions_num_pics').attr("value", images);
		ShowImages();
		
	}
  //Compute the Cost
  if (document.getElementById('Total') != null) ComputeTally();
}
function TextMessagingCost() {
	var text_cost_box = document.getElementsByName('text_amount');
	var text_amount = text_cost_box[0].value;
	for (var i=0; i < text_cost_box.length; i++) {
		if (text_cost_box[i].checked) text_amount = text_cost_box[i].value;
	}
	
	//$('#debug').html('Things! '+ text_amount);
	$('#enable_text_meta_cost').attr("value", $('#radio_text_amount_'+text_amount).attr('cost'));
	if (document.getElementById('Total') != null) ComputeTally();
}
function TextMessaging() {
	if ($('#Text_enable_text').attr("checked")) {
		$('#text_amount_tr').show();
		$('#text_cellphone_tr').show();
	} else {
		$('#text_amount_tr').hide();
		$('#text_cellphone_tr').hide();
	}
	//if (document.getElementById('Total') != null) ComputeTally();
}

//--------------- Tally up all subtotals ------------
function ComputeTally() {
	$('.number').each(Tally);
	$('.image').each(Tally);
	$('.checkbox').each(Tally);
}

function Tally() {
	var name = $(this).attr("name");
	//Check if we need to add this
	var mult_id = name +"_meta_cost";
	if (!$('#'. mult_id)) return;
	
	//Id's of related Information
	var sub_id = name +"_subtotal";
	var box_id = name +"_subtotal_box";
	var max_id = name +"_meta_max";
	var err_id = name +"_error";
	var prm_id = name +"_prompt";
	var pend_id = name +"_pending";
	var num = 0;
	
	
	
  //-Image
	if ($(this).hasClass('image')) {
		//Image number:
		var img_num = parseFloat($(this).attr("id").match(/\d+/gi));
		
		//-First Free Pics Special
		if (img_num > freePics) {
			//if ($(this).attr("value") != "")
			num = 1;
		}
		//Yard sign special
		if (YardSign()) num = 0;
		err_id = 'Images_'+ name +'_error';
		
	} else if ($(this).hasClass('checkbox')) {
  //-CheckBox
		if ($(this).attr("checked")) {
			num = 1;
			//debug:$('#debug').append('<br />'+ name+':'+$('#'+mult_id).attr("value"));
		}
	} else {
  //-Text
		num = ParseInt($(this).attr("value"));
		//-Stop non-numbers from being entered
		if (!IsNumeric(num)) {
			$(this).attr("value", "");
			num = 0;
		}
		//-Check for max
		if ($('#'+ max_id).attr("value") != "") {
			var max = parseFloat($('#'+ max_id).attr("value"));
			if (num > max) {
				$(this).attr("value", max);
				num = max;
			}
			
		}
		//Num Pics minus the freepics
		if ($(this).attr("name") == "num_pics") {
			if (num > freePics) num -= freePics;
			else num = 0;
			if (YardSign()) num = 0;
		}
		if ($(this).attr("name") == "yard_sign") {
			$('.image').each(Tally);
			$('#ImageOptions_num_pics').each(Tally);
		}
		if ($(this).attr("name") == "twosidedirect_sign") {
			if (num == 0) $('#message_tr').hide();
			else $('#message_tr').show();
		}
	}
	if (num == 0) {
		$('#'+ sub_id).html("");
		$('#'+ box_id).hide();
		$('#'+ pend_id).hide();
	} else {
		var cost = num  * parseFloat($('#'+mult_id).attr("value"));
		$('#'+ sub_id).html(format(cost));
		$('#'+ box_id).show();
		$('#'+ pend_id).show();
	}
	if (initialized) {
		$('#'+ err_id).html("");
		$('#'+ err_id).hide();
		$('#'+ prm_id).removeClass('error')
		$(this).removeClass('error');
	}
	Total();
}
function YardSign() {
	var yardsign = ParseInt($('#FSBOSigns_yard_sign').attr("value"));
	var send_pics = document.getElementsByName('send_pics');
	if (IsNumeric(yardsign) && yardsign > 0 && send_pics_method != "NONE") {
		$('#costBox').show();
		return true;
	}
	
	var calgaryHome = $('#Calgary_home_submission').attr("checked");
	//$('#phpDebug').html('calgary Home?'+calgaryHome);
	if (calgaryHome == true && send_pics_method != "NONE") {
		$('#costBox').show();
		return true;
	}
	
	
	$('#costBox').hide();
	return false;
}

function Total() {
	//$("#imgerror").append("<br />TOTAL");
	var tot = baseCost;
	//Collect all subtotals
	$('.FSBOSigns_subtotal').each(function() {
		if (IsNumeric($(this).html())) {
			tot += parseFloat($(this).html());
		}
	});
	$('.ImageOptions_subtotal').each(function() {
		if (!($(this).attr("id") == "num_pics_subtotal" && YardSign())) {
			if (IsNumeric($(this).html())) {
				tot += parseFloat($(this).html());
			}
		}
	});
	$('.Calgary_subtotal').each(function() {
		if (IsNumeric($(this).html())) {
			tot += parseFloat($(this).html());
		}
	});
	$('.Ontario_subtotal').each(function() {
		if (IsNumeric($(this).html())) {
			tot += parseFloat($(this).html());
		}
	});
	$('.Text_subtotal').each(function() {
		if (IsNumeric($(this).html())) {
			tot += parseFloat($(this).html());
		}
	});
	
	if (tot > baseCost) $('#TotalText').html("Total: $");
	$('#Total').html(format(tot));
}

//Initialize Images Uploader
function initImages() {
	if (!initialized) {
		$('#Images').hide();
		images = parseFloat($('#ImageOptions_num_pics').attr("value"));
		
		if (images == 0) {
			images = 1;
			$('#ImageOptions_num_pics').attr("value", images);
		}
		//Store All Image Rows
		for (i=1; i <= maxImages; i++) {
			//Append Swap Box
			$('#img'+ i +'_prompt').append('<br /><span id="img'+ i +'_swapbox" class="swapBox"></span>');
			AddSwapOptions('img'+i);
			
			imageRows[i] = $('#img'+ i +'_tr').html();
			
			if (i > images) {
				$('#img'+ i +'_tr').hide();
				$('#img'+ i +'_tr').html("");
				
			}
		}
		$('#Images').append('<a href="'+ uploadsp +'#" id="addImage" class="icon iconhover" style="cursor: pointer"><span class="noicon">[+</span>Add Image</span><span class="noicon">]</span></a>');
		$('#Images').append('<span id="removeImage" class="icon iconhover" style="cursor: pointer"><span class="noicon">[-</span>Remove Image<span class="noicon">]</span></span></a>');
		
		$('#addImage').click(AddImageClick);
		$('#removeImage').click(RemoveImageClick);
		
		if (images < 2) $('#removeImage').hide();
		if (images == maxImages) $('#addImage').hide();
		
		$('#Images').show();
		imageShow = true;
	}
}

//Images
function ShowImages() {
	if (imageShow) return;
	if (images == 0) {
		AddImage();
	} else {
		imageRecall = parseFloat($('#ImageOptions_num_pics').attr("value"));
		images = 0;
		for (i=1; i <= imageRecall; i++) {
			document.getElementById('debug').innerHTML += images+"->";
			AddImage();
		}
		images = imageRecall;
	}
	imageShow = true;
	$('#Images').slideDown();
	
}

function HideImages() {
	//Don't Hide the images twice in a row
	if (!imageShow) return;
	imageRecall = images;
	while (images > 0) RemoveImage();
	$('#Images').hide();
	imageShow = false;
}

function AddImageClick() {
	//$("#imgerror").append("<br />Add Image click");
	if (ImageClick) return false;
	ImageClick = true;
	AddImage();
	$('#addImage').attr('href', ''+ uploadsp +'#loc_img'+images);
	ComputeTally();
	ImageClick = false;
}
function RemoveImageClick() {
	RemoveImage();
	ComputeTally();
}
function AddSwapOptions(id) {
	var img = parseFloat(id.match(/\d+/gi));
	if (!IsNumeric(img)) img = ParseInt(img);
	//debug:$('#debug').append('<br />['+ id +'Add swap box to: #img'+ img +'_prompt['+ typeof(img) +'Previous(' + (img - 1) + ')NExt('+ (img + 1) +')ISNUM?('+ IsNumeric(img) +')' );
	if (img < 1 || img > images) return;
	
	var thumbimg = $('#thumbimg'+ img).attr('src');
	
	
	
	//Clear Our Swap
	$('#img'+ img +'_swapbox').html("");
	
	if (images > 1) {
		$('#img'+ img +'_swapbox').append('<a href="'+ uploadsp +'#loc_img' + (img - 1) + '" id="img'+ img +'_pull" class="icon iconhover picOps removePictureSlot" title="Remove this Image"><span class="noicon">[-</span><span>Remove</span><span class="noicon">]</span></a>');
		$('#img'+ img +'_pull').click(function() { PullImage(img); return false; });
	}
	if (typeof(thumbimg) == "undefined" || thumbimg == "") return;
	//Add our Swap
	if (img > 1) { // Swap up
		$('#img'+ img +'_swapbox').append(' <a href="'+ uploadsp +'#loc_img' + (img - 1) + '" id="img'+ img +'_swapup" class="icon iconhover picOps swap swapUp" title="Move Image Up"><span class="noicon">]</span><span>Move up</span><span class="noicon">]</span></a>');
		$('#img'+ img +'_swapup').click(function() { SwapImages(img, (img - 1)); return false;});
	}
	if (img < images) {
		$('#img'+ img +'_swapbox').append(' <a href="'+ uploadsp +'#loc_img'+ (img + 1) +'" id="img'+ img +'_swapdown" class="icon iconhover picOps swap swapDown" title="Move Image Down"><span class="noicon">[</span><span>Move Down</span><span class="noicon">]</span></a>');
		$('#img'+ img +'_swapdown').click(function() { SwapImages(img, (img + 1)); return false; });
	}
}
function PullImage(img) {
	$('#img'+ img +'_tr').hide();
	SwapImages(img, images);
	for (i=img; i < images - 1; i++) SwapImages(i, i+1);
	RemoveImage();
	$('#img'+ img +'_tr').show();
	AddSwapOptions("img"+img);
}

function SwapImages(img, img2) {
	if (upQueue.length) {
		alert("Please Allow images to finish uploading before swapping.");
		return;
	}
	//Make a placeholder
	//$('#debug').append('<br />Swap'+ img);
	
	ClearImageError('img'+img);
	ClearImageError('img'+img2);
	
	var meta = $('#img'+ img +'_meta').attr('value');
	var thumbimg = $('#thumbimg'+ img).attr('src');
	var img_file = $('#img'+ img +'_file').attr('value');
	
	if (typeof(thumbimg) == "undefined" || thumbimg == "") {
		thumbimg = "";
		$('#deleteimg'+ img2).hide();
		$('#thumbimg'+ img2).hide();
		
	} else {
		$('#deleteimg'+ img2).show();
		$('#thumbimg'+ img2).show();
	}
	
	var newSrc = $('#thumbimg'+ img2).attr('src');
	if (typeof(newSrc) == "undefined" || newSrc == "") {
		newSrc = "";
		$('#deleteimg'+ img).hide();
		$('#thumbimg'+ img).hide();
	} else {
		$('#deleteimg'+ img).show();
		$('#thumbimg'+ img).show();
	}
	
	//$('#debug').append('<br />Swap'+ img+'['+ meta +']['+ newSrc +']['+ img_file +']');
	
	//Swap
	$('#img'+ img +'_meta').attr('value', $('#img'+ img2 +'_meta').attr('value'));
	$('#thumbimg'+ img).attr('src', newSrc);
	$('#img'+ img +'_file').attr('value', $('#img'+ img2 +'_file').attr('value'));
	
	$('#img'+ img2 +'_meta').attr('value', meta);
	$('#thumbimg'+ img2).attr('src', thumbimg);
	$('#img'+ img2 +'_file').attr('value', img_file);
	
	AddSwapOptions("img"+img);
	AddSwapOptions("img"+img2);
}

function AddImage() {
	//More Allowed?
	if (images == maxImages) return;
	
	images++;
	//Restore Row
	var imgHTML = imageRows[images];
	
	$('#img'+ images +'_tr').html(imgHTML);
	AddSwapOptions("img"+ images);
	AddSwapOptions("img"+ (images - 1));
	
	$('#img'+ images +'_tr').show();
	
	$('#img'+ images +'').change(changeBind);
	
	//Update Image form submit number
	$('#ImageOptions_num_pics').attr("value", images);
	
	//remove [+]
	if (images == maxImages) {
		$('#addImage').hide();
	}
	//show [-]
	if (images > 1)	$('#removeImage').show();
	
	$('#deleteimg'+ images).click(function() {
		clearImg('img'+ images);
	});

}
function ClearImageError(image) {
	$('#Images_'+ image +'_error').hide();
	$('#error'+ image).hide();
	
	$('#Images_'+ image +'_error').html();
	$('#error'+ image).html();
	
	$('#'+ image).removeClass('error');
	$('#'+ image +'_prompt').removeClass('error');
	$('#'+ image +'_meta').removeClass('error');
}

function RemoveImage() {
	//Clear Error
	ClearImageError('img'+images);
	
	//Store & Hide
	imageRows[images] = $('#img'+ images +'_tr').html();
	$('#img'+ images +'_tr').hide();
	$('#img'+ images +'_tr').html("");
	
	
	//Update Image Form Value
	images--;
	AddSwapOptions('img'+images);
	
	$('#ImageOptions_num_pics').attr("value", images);
	if (images < 2)
		$('#removeImage').hide();
	$('#addImage').show();
}


//----------------------------Auto Region Selection!----------------------------//
function AutoRegion() {
	//Check for existing Element
	if (document.getElementById('First_list_region')) {
		baseCost = parseFloat($('#Total').html());
		//Do a click region to make things ready
		clickRegion();
		//Bind the changer
		//debug:$('#debug').append("<br />Bind Changer");
		$('#First_list_region').change(clickRegion);
		
		//debug:$('#debug').append("<br />Bind SecondChanger");
		$('.region').change(GetSubRegionCost);
		regionInit = true;
	}
}
function clickRegion() {
	//Fetch the value of the region box
	var val = $('#First_list_region').attr('value');
	//debug:$('#debug').append("<br />Click!["+ val +"]");
	//Hide All other sub-regions and unname them
	$('.hidder').hide();
	$('.region').removeAttr("name");
	$('.region').attr('disabled', 'disabled');
	
	//Hide the Maps
	$('.h_hidder').hide();
	
	//Show the sub region and re-name it
	if (val != "") {
		$('#'+ val).show();
		$('#'+ val +"_region").attr('disabled', '');
		$('#'+ val +"_region").attr("name", "region");
				
		//debug:$('#debug').append("GetSUb");
		GetSubRegionCostId(val +"_region");
	} else {
		$('#Total').html(format(baseCost));
		val = 'canada';
	}
	if (regionInit) $('#notFound').hide();
	$('#h_'+ val).show();
	//debug:$('#debug').append("Done");
}
function GetSubRegionCost() {
	GetSubRegionCostId($(this).attr('id'));	
}
function GetSubRegionCostId(id) {
	if (document.getElementById('Total') == null) return;
	var val = $('#'+id).attr('value');
	//debug:$('#debug').append("<br />"+id+"?"+val);
	if (!val) {
		$('#Total').html(format(baseCost));
		return;
	}
	var name = $('#'+id).attr('name'); 
	
	var cost = parseFloat($('#'+name+"_"+val).attr('cost'));
	
	//debug:$('#debug').append("="+ name +"~"+ cost);
	num = id.match(/\d+/gi);
	if (IsNumeric(cost) && cost != 0) {
		$('.'+num+'_subtotal').html(format(cost));
		$('.'+num+'_subtotal_box').show();
		
	} else {
		$('.'+num+'_subtotal_box').hide();
		cost = 0;
	}
	//debug:$('#debug').append("--base"+ baseCost +"~num"+ num);
	
	var tot = baseCost + cost;
	$('#Total').html(format(tot));
}

//--Utility Functions
function format(val) {
  sign = val < 0 ? "-":"";
  rval = Math.abs(Math.round(val*100));
  str = rval.toString();
  if(rval < 10) str = "0.0"+str;
  else if(rval < 100) str = "0."+str;
  else str = str.substring(0, str.length-2)
     + "." + str.substring(str.length-2, str.length);
  return sign+str;
}
function ParseInt(n) {
	return n.match(/^\d+$/gi);
}

function IsNumeric(n) {
	return !isNaN(parseFloat(n));
}
