// JavaScript Document
function toggleFocus(el,val){
	if(el.value == val){
		el.value = '';
	}
}

function toggleBlur(el,val){
	if(el.value == ''){
		el.value = val;
	}
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function addLoginToggle(){
	if($("#loginToggle").length > 0){
		$("#cancelLogin").bind("click",function(e){
				$("#login_form").hide();
				$("#loginToggle").show();
				return false;
			});
		$("#loginToggle").bind("click",function(e){
				$("#login_form").show();
				$(this).hide();
				return false;
			});
	}
}

function gunSelector(){
	$("#timeframe input").bind("click",function(t){
			var year = $("[name=years]:checked").val();
			var str = year + " year";
			str += (year == "1") ? "" : "s";
			$("#term").html(str);
		});
	
	function bindGunModel(){
		$("#gun_model").bind("change",function(e){
				if($(this).val() == "unlisted"){
					$("#other_model").show();
				} else {
					$("#other_model").hide();
				}
			});
	}
	function bindGunCaliber(){
		$("#gun_caliber").bind("change",function(e){
				if($(this).val() == "unlisted"){
					$("#other_caliber").show();
				} else {
					$("#other_caliber").hide();
				}
			});
	}
	
	if($("#gun_make").length > 0){
		$("#gun_make").bind("change",function(e){
				$("#gun_model").attr("disabled","disabled");
				if($(this).val() == "unlisted"){
					$("#make_other").show();
				} else {
					$("#make_other").hide();
				}
				$.ajax({
						type:"POST",
						url:"/js/mg_ajax.php",
						data:"action=updateModels&make="+$(this).val(),
						success: function(d){
							$("#models").html(d);
							bindGunModel();
							if($("#gun_model").val() == "unlisted"){
								$("#other_model").show();
							} else {
								$("#other_model").hide();
							}
						}
					});
			});
	}
	if($("#gun_model").length > 0){
		bindGunModel();
	}
	if($("#gun_caliber").length > 0){
		bindGunCaliber();
	}
}

function showThumb(id){
	$("#thumb"+id).show();
}
function hideThumb(id){
	$("#thumb"+id).hide();
}

function markGun(id,which){
	var whichText = (which.indexOf("delete") != -1) ? which+"d" : which;
	if(confirm("Are you sure you want to mark this gun "+whichText+"?")){
		$.ajax({
			type: "POST",
			url: "/js/mg_ajax.php",
			data: "action=mark_"+which+"&gun="+id
		});
		var swap = (which.indexOf("un") == -1) ? "un"+which : which.replace("un","");
		var swapText = (swap.indexOf("sold") != -1) ? "mark "+swap : swap;
		$("#"+which+id).html("<a href=\"/admin/"+swap+"/"+id+"/\" onclick=\"return markGun('"+id+"','"+swap+"');\">"+swapText+"</a>");
		$("#"+which+id).attr("id",swap+id);
	}
	return false;
}

function inventoryRows(){
	var rows = $("#inventory tr:not(:first)");
	var origClass = "";
	$.each(rows,function(r){
			/*$(this).children("td:not(:first)").bind("click",function(c){
					var rowID = $(this).parents("tr").attr("id");
					rowID = rowID.replace("stock_row","");
					window.location = "/details/"+rowID+"/";
					return false;
				});*/
			$(this).bind("click",function(c){
					var url = $(this).children("td:last").children("a").attr("href");
					window.location = url;
					return false;
				});
			
			$(this).hover(
				function(i){
					origClass = ($(this).hasClass("zebra")) ? "zebra" : "";
					$(this).removeClass();
					$(this).addClass("inv_hover");
				},
				function(o){
					$(this).removeClass();
					$(this).addClass(origClass);
					origClass = "";
				}
			);
		});
	/*
	var firsts = $("#inventory tr td:first").bind("click",function(c){
			return false;
		}); */
		
	var images = $(".photo_icon");
	$.each(images,function(p){
			var imgSrc = $(this).attr("href");
			imgSrc = imgSrc.replace("/files/images/","/files/images/thumbs/thumb_");
			var imgID = $(this).attr("id");
			imgID = imgID.replace("photo","");
			$(this).before("<div class=\"thumb\" id=\"thumb"+imgID+"\" style=\"display:none;\"><img src=\""+imgSrc+"\" alt=\"\" /></div>");
			
			$(this).hover(
				function(i){
					var row = $(this).attr("id");
					row = row.replace("photo","");
					showThumb(row);
				},
				function(o){
					var row = $(this).attr("id");
					row = row.replace("photo","");
					hideThumb(row);
				}
			);
		});
}

hs.graphicsDir = '/js/highslide/graphics/';
hs.outlineType = 'rounded-white';
hs.captionEval = 'this.thumb.title';
function setupHS(){
	$("#content a.highslide").bind("click", function(s){
			return hs.expand(this);
		});
}

var add_btn = "";
var save_btn = "";

function bindAll(){
	$("legend#gun_legend").bind("click", function(d){
			$("fieldset#gun").hide();
			$("fieldset#all").show();
			$("#find_all").val("1");
		});
	$("legend#all_legend").bind("click", function(d){
			$("fieldset#gun").show();
			$("fieldset#all").hide();
			$("#find_all").val("0");
		});
	$("#upload_btn").bind("click", function(u){
			add_btn = "upload";
			save_btn = "upload";
			if($("#new_photo").val() == ""){
				alert("Select an Image");
				return false;
			} else {
				$("#photo_wait").show();
				$("#upload_btn").hide();
			}
			return true;
		});
	if($("#mg_login").length > 0){
		$("#mg_email").focus();
		$("#mg_forgot").bind("click",function(e){
				return forgotPassword();
			});
		$("#mg_login").bind("submit",function(e){
				return checkLogin();
			});
	}
	if($("#new_gun").length > 0){
		$("#new_gun").bind("submit",function(g){
				return confirmAddGun();
			});
	}
	
	if($("#update_gun").length > 0){
		$("#update_gun").bind("submit",function(g){
				return confirmSaveGun();
			});
	}
	if($("#add_btn").length > 0){
		$("#add_btn").bind("click",function(g){
				add_btn = "add";
			});
	}
	if($("#save_btn").length > 0){
		$("#save_btn").bind("click",function(g){
				save_btn = "save";
			});
	}
	if($("#staging_btn").length > 0){
		$("#staging_btn").bind("click",function(g){
				add_btn = "staging";
				save_btn = "staging";
			});
	}
	if($("#calc_toggle a").length > 0){
		$("#calc_toggle a").bind("click",function(g){
				if($("#calculator:visible").length > 0){
					$("#calculator").hide(300);
					$("#calc_toggle a").html("Show Payment Calculator");
				} else {
					$("#calculator").show(300);
					$("#calc_toggle a").html("Hide Payment Calculator");
				}
				return false;
			});
	}
	
	if($("#payment_calculator").length > 0){
		$("#payment_calculator").bind("submit", function(g){
				calculate();
				return false;
			});
		$("#trade").bind("keyup", calculate);
//		$("#trade").bind("blur", calculate);
		$("#rate").bind("keyup", calculate);
//		$("#rate").bind("blur", calculate);
		$("#term").bind("change", calculate);
//		$("#term").bind("blur", calculate);
	}
	
	if($("#blast").length > 0){
		$("#blast").bind("click",function(g){
				if($(this).attr("checked")){
					$("#deDupe").attr("checked","checked");
					$("#select_columns input").attr("disabled","disabled");
					$("#select_columns").hide();
					$("#range").val("last");
				} else {
					$("#select_columns input:disabled").removeAttr("disabled");
					$("#select_columns").show();
					$("#range").val("");
				}
			});
	}
}

function confirmSaveGun(){
	if(save_btn != "upload"){
		if($("#price").val() == "" || $("#gun_make").val() == ""){
			alert("Fill in all required fields.");
			return false;
		}
		
		if($("#new_photo").val() != ""){
			if(!confirm("It appears you have selected a photo to upload. If you wish to upload it, use the \"Upload Image\" button before adding this gun.\n\nWould you like to continue without uploading the image in the upload field?")){
				return false;
			}
		}
		
		if($("#images").val() == ""){
			return confirm("Are you sure you want to save your changes without any images?");
		}
	}
	return true;
}

function confirmAddGun(){
	if(add_btn != "upload"){
		if($("#price").val() == "" || $("#gun_make").val() == ""){
			alert("Fill in all required fields.");
			return false;
		}
		
		if($("#new_photo").val() != ""){
			if(!confirm("It appears you have selected a photo to upload. If you wish to upload it, use the \"Upload Image\" button before adding this gun.\n\nWould you like to continue without uploading the image in the upload field?")){
				return false;
			}
		}
		
		if($("#images").val() == ""){
			return confirm("Are you sure you want to add a gun with no images?");
		}
	}
	return true;
}

function calculate(){
	//
	$("#months").html($("#term").val());
	var rate = ($("#rate").val() != "" && !isNaN($("#rate").val())) ? parseFloat($("#rate").val()) : 1.5;
	var trade = ($("#trade").val() != "" && !isNaN($("#trade").val())) ? parseFloat($("#trade").val()) : 0;
	var term = ($("#term").val() != "" && !isNaN($("#term").val())) ? parseFloat($("#term").val()) : 12;
	var price = ($("#gun_price").val() != "" && !isNaN($("#gun_price").val())) ? parseFloat($("#gun_price").val()) : 0;
	
	if(price <= 0){
		alert("There is an error in the form (gun price is "+price+").");
	} else {
		if(trade > price){
			alert("Trade amount is greater than price of the gun.");
		} else {
			var principle = price - trade;
			var calc_rate = (price < 750 && term >= 12) ? rate / 1200 : 0;
			var interest = principle * calc_rate * term;
			var total = (principle + interest) / term;
			total = round(total,2);
			total = number_format(total);
			$("#payments").html(total);
		}
	}
}

// http://kevin.vanzonneveld.net
function round ( val, precision ) { 
    var precision = (round.arguments.length > 1) ? round.arguments[1] : 0;
    return Math.round(val * Math.pow(10, precision))/Math.pow(10, precision);
}
function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function checkLogin(){
	if(validateLogin()){
		var email = $("#mg_email").val();
		var pass = $("#mg_pass").val();
		
		var result = $.ajax({
			type: "POST",
			async: false,
			url: "/js/mg_ajax.php",
			data: "action=checkLogin&email="+email+"&pass="+pass
		}).responseText;
		
		if(result == ""){
			hideError();
			return true;
		} else {
			showError(result);
			return false;
		}
	}
	return false;
}

function validateLogin(){
	var e = $("#mg_email").val();
	var p = $("#mg_pass").val();
	if($.trim(e) == ""){
		showError("Enter your email address.");
		$("#mg_email").val("");
		$("#mg_email").focus();
		return false;
	}
	if($.trim(p) == ""){
		showError("Enter your password.");
		$("#mg_pass").val("");
		$("#mg_pass").focus();
		return false;
	}
	return true;
}

function checkEmail(email){
	var result = $.ajax({
		type: "POST",
		async: false,
		url: "/js/mg_ajax.php",
		data: "action=checkEmail&email="+email
	}).responseText;
	return (result == "") ? null : result;
}

function showError(msg){
	if(msg){
		if($("#error_msg").html() == msg){
			$("#error_msg").show("fast");
			$("#error_msg").animate({
					fontSize:"14px"
				}, "fast");
			$("#error_msg").animate({
					fontSize:"12px"
				}, "fast");
		} else {
			$("#error_msg").html(msg);
			$("#error_msg").show("fast");
		}
	}
}

function hideError(){
	$("#error_msg").hide("fast");
}


function forgotPassword(){
	var mg_email = $("#mg_email").val();
	if($.trim(mg_email) == ""){
		showError("Enter your email address.");
		$("#mg_email").val("");
		$("#mg_email").focus();
	} else {
		var verifyEmail = checkEmail(mg_email);
		if(verifyEmail == null){
			hideError();
			emailPassword(mg_email);
		} else {
			showError(verifyEmail);
			$("#mg_email").focus();
		}
	}
	return false;
}

function emailPassword(email){
	if(0){
		window.location = "/login/forgot/";
	}
}

function clearTmp(modify){
	if(confirm("Are you sure you want to delete these images?")){
		$.ajax({
			type: "POST",
		//	async: false,
			url: "/js/mg_ajax.php",
			data: "action=clearTmp"
		});
		if(modify){
			$("#tmp_images").html('');
			if($("#the_photos").html() == ""){
				$("#the_photos").html("No photos uploaded yet.");
			}
			$("#up_msg").hide();
			$("#clear_images").hide();
		} else {
			$("#images").val("");
			$("#the_photos").html("No photos uploaded yet.");
			$("#up_msg").hide();
			$("#clear_images").hide();
		}
	}
	return false;
}

function deletePhoto(id,file,tmp){
	if(confirm("Are you sure you want to delete this photo?")){
		var divID = file.replace(".jpg","");
		$("#manage_image"+divID).remove();
		$.ajax({
			type: "POST",
		//	async: false,
			url: "/js/mg_ajax.php",
			data: "action=deleteImage&id="+id+"&file="+file+"&tmp="+((tmp) ? "1" : "0")
		});
		var newVal = $("#images").val();
		newVal = newVal.replace(file+";","");
		newVal = newVal.replace(";"+file,"");
		newVal = newVal.replace(file,"");
		$("#images").val(newVal);
		$("#up_msg").hide();
		if(newVal == ""){
			$("#the_photos").html("No photos uploaded yet.");
		}
	}
	return false;
}


function sendTestEmail(){
	var oEditor = FCKeditorAPI.GetInstance('newsletter_content');
	var emailContent = escape(oEditor.GetXHTML(oEditor.FormatOutput));
	var testEmail = $("#test_email").val();
	if($("#from_name").val() == "" || $("#subject").val() == "" || emailContent == "" || testEmail == ""){
		alert("Please fill in all required fields.");
	} else {
		$.ajax({
				type: "POST",
			//	async: false,
				url: "/js/mg_ajax.php",
				data: 'action=sendTestEmail&addr='+testEmail+'&newsletter_content='+emailContent+'&subject='+$("#subject").val()+'&from_name='+$("#from_name").val()+'&reply_to='+$("#reply_to").val(),
				success: function(d){
						$("#test_message").html(d);
						$("#test_message").show();
					}
			});
	}
	return false;
}

function getPeople(warn){
	var pass = false;
	if(warn){
		if(confirm("Are you sure you want to load these emails?\nDouble check to make sure they are not already loaded or\nthe email will be sent to all your subscribers twice.")){
			pass = true;
		}
	} else {
		pass = true;
	}
	if(pass){
		var temp = $("#get_emails").html();
		$("#get_emails").html("Please wait...");
		var sep = ($("#recipients").val().indexOf(",") < 0) ? ";" : ",";
		$.ajax({
				type: "POST",
			//	async: false,
				url: "/js/mg_ajax.php",
				data: 'action=getSubscribers&sep='+sep,
				success: function(d){
						var addresses = d;
						if($("#recipients").val() != ""){
							addresses = $("#recipients").val() + sep + "\n" + addresses;
						}
						if($("#recipients").val().indexOf(addresses) < 0){
							$("#recipients").val(addresses);
						} else {
							if($("#recipients").val() == ""){
								alert("Your session has ended. Please re-log in to complete this action.");
							}
						}
						
						$("#get_emails").html('');
					}
			});
	}
	return false;
}


function customSort(el){
	var pass = false;
	$(el).children("select").each(function(r){
			if($(this).val() != ""){
				pass = true;
			}
		});
	
	if(pass){
		return true;
	} else {
		alert('You must select at least 1 value.');
		return false;
	}
	return false;
}

$(document).ready(function(){
		bindAll();
		setupHS();
		addLoginToggle();
		gunSelector();
		inventoryRows();
		$(".sort").bind("change",function(s){
				$(".sort").val($(this).val());
				if($(this).val() == "custom"){
					$(".custom_view").show();
					$(".keyword_search").hide();
				} else if($(this).val() == "keyword") {
					$(".keyword_search").show();
					$(".custom_view").hide();
				} else {
					$(".custom_view").hide();
					$(".keyword_search").hide();
					$(this).parents("form").submit();
				}
			});
/*		$(".custom_view form").bind("submit", function(r){
				return customSort($(this));
			});*/
		$("#print_info").bind("click",function(c){
				window.print();
				return false;
			});
		$(".thumbnail").bind("click",function(t){
				var src = $(this).attr("href");
				$("#main_photo img").attr("src",src);
				$(".selected").removeClass("selected");
				$(this).addClass("selected");
				return false;
			});
		$("#unsubscribe").bind("submit", function(e){
				$("#unsub_msg").html('');
				$.ajax({
					type: "POST",
				//	async: false,
					url: "/js/mg_ajax.php",
					data: "action=unsubscribe_user&email="+$("#email_address").val(),
					success: function(d){
							$("#unsub_msg").html(d);
						}
				});
				return false;
			});
		$("#reset_pass").bind("submit", function(e){
				$("#reset_msg").html('');
				if($("#new_pass").val() == "" || $("#verify_pass").val() == "" || $("#current_pass") == ""){
					$("#reset_msg").html('<span style="color:#F00;">All fields are required.</span>');
				} else {
					if($("#new_pass").val() != $("#verify_pass").val()){
						$("#reset_msg").html('<span style="color:#F00;">New passwords don\'t match.</span>');
					} else {
						$.ajax({
							type: "POST",
						//	async: false,
							url: "/js/mg_ajax.php",
							data: "action=reset_pass&current="+$("#current_pass").val()+"&new="+$("#new_pass").val()+"&verify="+$("#verify_pass").val(),
							success: function(d){
									$("#reset_msg").html(d);
									if(d=="Password updated."){
										$("#current_pass").val('');
										$("#new_pass").val('');
										$("#verify_pass").val('');
									}
								}
						});
					}
				}
				return false;
			});
	} // end function
); // end ready