function verify_textfield(fieldObj, objRegExp, msg, optional) {
    if (optional && fieldObj.value == "")
            return true;

    if (objRegExp.test(fieldObj.value))
        return true;

  alert(msg + " field contents are invalid.");
  fieldObj.focus();
  return false;
}

function verify_dropdown(obj, msg) {
    if (obj.options[obj.selectedIndex].value != "")
        return true;

  alert(msg + " selection is required.");
  obj.focus();
  return false;
}

function verify_support_form(frm)
{
    if (!verify_textfield(frm.customer_name, /^.+$/i, "Name", false)) return false;
    if (!verify_textfield(frm.customer_email, /^[-a-z0-9_\.]+@[-a-z0-9_\.]+$/i, "Email", false)) return false;
//    if (!verify_textfield(frm.order_number, /^CF-[\d][01]\d[0-3]\d-\d{4}0$/i, "Order number", true)) return false;

    if (!verify_dropdown(frm.subject, "Subject")) return false;

    return true;
}

function verify_login_form(frm)
{
    if (!verify_textfield(frm.user_email, /^[-a-z0-9_\.]+@[-a-z0-9_\.]+$/i, "Email", false)) return false;
    if (!verify_textfield(frm.user_password, /^.+$/i, "Password", false)) return false;

    return true;
}

function verify_coupon_form(frm) {
    if (!verify_textfield(frm.customer_email, /^[-a-z0-9_\.]+@[-a-z0-9_\.]+$/i, "Email", false)) return false;
    
    return true;
}

function verify_quote_form(frm)
{
    if (!verify_textfield(frm.customer_name, /^.+$/i, "Name", false)) return false;
    if (!verify_textfield(frm.customer_email, /^[-a-z0-9_\.]+@[-a-z0-9_\.]+$/i, "Email", false)) return false;

    return true;
}

function verify_pricematch_form(frm)
{
    if (!verify_textfield(frm.competitor_price, /^\$?[0-9\.,]+$/i, "Competitor Price", false)) return false;
    if (!verify_textfield(frm.competitor_info, /.+/i, "Information", false)) return false;
    if (!verify_textfield(frm.customer_name, /^.+$/i, "Name", false)) return false;
    if (!verify_textfield(frm.customer_email, /^[-a-z0-9_\.]+@[-a-z0-9_\.]+$/i, "Email", false)) return false;

    return true;
}

function verify_create_form(frm)
{
    if (!verify_textfield(frm.user_email, /^[-a-z0-9_\.]+@[-a-z0-9_\.]+$/i, "Email", false)) return false;
    if (!verify_textfield(frm.user_password, /^.+$/i, "Password", false)) return false;
    if (!verify_textfield(frm.user_password_confirm, /^.+$/i, "Password", false)) return false;

    if (frm.user_password.value != frm.user_password_confirm.value) {
        alert("Passwords do not match.");
        frm.user_password_confirm.focus();
    	return false;
    }

    return true;
}
function loadImage(path)
{
  previewImage = new Image();
  previewImage.onload = openWindow;
  previewImage.path = path;
  previewImage.src = path;
}

function openWindow()
{
  var path = "pic_viewer.php?path=" + encodeURIComponent(previewImage.path);
  var conf = "top=100,left=100,width=" + (previewImage.width + 0) + ", height=" + (previewImage.height + 4 + 20) + ", scrollbars=0";

  window.open(path, "", conf);
}

function onloadHandler() {
	var frmLogin = document.forms["frmLogin"];
	if (frmLogin && frmLogin.user_email.value != '') {
		frmLogin.user_password.focus();
	}
}

function phoneFormFieldHandler(obj)
{
	var phoneNumber = new String(obj.value);
	phoneNumber = phoneNumber.replace(/[^0-9]/g, "");
	alert(phoneNumber[0]);
	if (phoneNumber.length == 11 && phoneNumber[0] == '1')
		phoneNumber = phoneNumber.substr(1);
	if (phoneNumber.length != 10)
		return;
	obj.value = "(" + phoneNumber.substr(0, 3) + ") " + phoneNumber.substr(3, 3) + "-" + phoneNumber.substr(6);
}

function highlightBrands(type) {
//	if (type == 1)
}

function handleShowcaseChange(brandID) {
	if (brandID == 0)
		return;
	var url = "/?bid=" + brandID;
	location.href = url;
}

function handleBrandChange(brandID, typeIDs, genderIDs) {
	var url = "/?results&p=1";
	if (brandID)
		url += "&bid=" + brandID;
	if (typeIDs && typeIDs.length > 0)
		if (typeIDs.length > 1)
			for(var i = 0; i < typeIDs.length; i++)
				url += "&tid[]=" + typeIDs[i];
		else
			url += "&tid=" + typeIDs[0];
	if (genderIDs && genderIDs.length > 0)
		for(var i = 0; i < genderIDs.length; i++)
			url += "&gid[]=" + genderIDs[i];
	location.href = url;
}

function handleFrameChange(frameID) {
	if (frameID == 0)
		return;
	if (isNaN(frameID))
		location.href = "/glasses/" + frameID;
	else
		location.href = "/?fid=" + frameID;
}

var DelayedThumbnails = new function() {
	var arr = [];

	this.init = function() {
		arr = $A(document.images).findAll(function(o) { return (o.getAttribute("actualsrc")); });
		this.load();
	};

	this.load = function() {
		arr.each(function(o, i) {
			var pos = Position.page(o)[1];
			if (pos < -200 || pos > 1200)
				return;
			o.src = o.getAttribute("actualsrc");
			o.removeAttribute("actualsrc");
			$(o).previous().remove();
			arr[i] = null;
		});
		arr = arr.compact();
	}
}

function handleHomeFilterChange(oLink, typeID, gender) {
	var arr = ['A', 'M', 'W', 'K'];

	var c = null;
	$A(oLink.parentNode.getElementsByTagName("A")).find(function(o, i) {
		if (oLink == o)
			return false;
		if (Element.hasClassName(o, "hilite")) {
			Element.removeClassName(o, "hilite");
			c = arr[i];
			return true;
		}
	});
	Element.addClassName(oLink, "hilite");
	
	Element.hide($("tblBrands_" + typeID + "_" + c));
	Element.show($("tblBrands_" + typeID + "_" + gender));

	document.cookie = "filter" + typeID + "=" + gender;
}

function formatDollarAmount(o) {
	o.value = formatCurrency(o.value);
}

function formatCurrency(origNum) {
	var num = origNum.toString().replace(/[^0-9\.]/g,'');
	if(num == "" || isNaN(num))
		return origNum;
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

var GC = new function()
{
	this.showInput = function() {
		$('frame_gc_input').value = '';
		Element.hide('frame_gc_step1');
		Element.show('frame_gc_step2');
		Element.hide('frame_gc_step3');
		$('frame_gc_input').focus();
	}

	this.apply = function() {
		var val = $('frame_gc_input').value;
		if (val == "mike") {
			Element.hide('frame_gc_step1');
			Element.hide('frame_gc_step2');
			Element.show('frame_gc_step3');
		} else {
			alert("Invalid Code. Please try again.")
			$('frame_gc_input').select();
		}
	}

	this.cancel = function() {
		Element.show('frame_gc_step1');
		Element.hide('frame_gc_step2');
		Element.hide('frame_gc_step3');
	}

	this.remove = function() {
		Element.show('frame_gc_step1');
		Element.hide('frame_gc_step2');
		Element.hide('frame_gc_step3');
	}
}

var Frame = new function()
{
	this.lens_price = 0;

	this.setLensPrice = function(price) {
		this.lens_price = price;
		this.handleStateChange($("checkoutForm"));
	}
	
	this.isPurchasable = function() {
		/*
		if ($("checkoutForm").lensType && $("checkoutForm").lensType.selectedIndex == 0) {
			if (confirm("Unless custom lenses are ordered, eyeglasses will come with a ");
			return false;
		}*/
		
		if ($("checkoutForm").frame_size_dynamic &&
				(($("checkoutForm").frame_size_dynamic.length > 1 && $A($("checkoutForm").frame_size_dynamic).find(function(radio) { return radio.checked; }).disabled) ||
				  $("checkoutForm").frame_size_dynamic.disabled)
			) {
			alert("Selected color/size combination is not available.");
			return false;
		}
		return true;
	}
	
	var getCost = function(s) {
		var p = oFrameInfo.premium;
		
		switch(s) {
			case "polarized":
				return (p?40:40);
			case "infrared":
				return (p?55:55);
			case "plastic":
				return (p?0:19);
			case "poly":
				return (p?0:39);
			case "photochromatic":
				return (p?49:75);
			case "highindex_standard":
				return (p?49:79);
			case "highindex_thinlite":
				return (p?99:119);
			case "glarefree_standard":
				return 19;
			case "glarefree_crizal":
				return (p?45:79);
			case "photochromatic_highindex_max":
				return (p?148:178);
		}
	}

	var frameColorTO = null;
	
	this.switchFrameColor = function(fid, sColor) {
		if (frameColorTO)
			window.clearTimeout(frameColorTO);
	
		frameColorTO = window.setTimeout(function() {
			Effect.BlindUp('frame_image_area', {queue: {position: 'end', scope: 'frame_color', limit: 2} });
		
			window.setTimeout(function() {
				new Ajax.Updater( { success: 'frame_image_area' },
									'/get_image_html.php', { method: 'get', 
															parameters: { fid: fid, color: sColor },
															onComplete: function() {}
														  }
				);
			}, 1000);
		}, 500);
	}

	this.handleLensTypeChange = function(oSelect) {
		switch(oSelect.value) {
			case "near":
			case "distance":
			case "progressive":			
				new Ajax.Request('/lenses_save_lenstype.php', 
				{
					parameters : Form.serialize(oSelect.form),
					onSuccess: function(transport) {
//						Modalbox.show('/get_lens_html.php?page=1&frame_id=' + oSelect.form.frame_id.value, {title: 'Lenses', width: 600});
						new Ajax.Updater('lensArea', '/get_lens_html.php', { parameters: { page: 1, frame_id: oSelect.form.frame_id.value }});
					}
				});
//				new Ajax.Updater("lensArea", "/get_lens_html.php", { parameters: { page: 1, frame_id: oSelect.form.frame_id.value }});
				break;
			case "":
			case "demo":
				break;
		}
	}

	this.handleFramePhotoLoad = function(oImage) {
		Effect.BlindDown('frame_image_area', {queue: {position: 'end', scope: 'frame_color', limit: 2} });
	}

	this.handleSizeChange = function(sSize, index, sUPC) {
		$("checkoutForm").upc.value = sUPC;
		$("checkoutForm").frame_size.value = sSize;
		$("size_checkbox_" + index).checked = true;

		this.handleStateChange($("checkoutForm"));
	}
	
	this.handleStateChange = function(oForm, oElement) {
		var extraCost = 0;
		var lensCost = 0;
		var coatingCost = 0;

		if (oForm.frame_color.length) {
			oColor = $A(oForm.frame_color).find(function(o) { return o.checked; });				
			nColorIndex = $A(oForm.frame_color).indexOf(oColor);
		} else {
			oColor = oForm.frame_color;
			nColorIndex = 0;
		}
// http://www.coolframes.com/?fid=4614 good one to test

		var oSizes = oFrameStyles[nColorIndex];
		if (oSizes.length == 1 && oSizes[0].size.toLowerCase() == "standard") {
			$("frame_size_area").update("Only available in one size.");
			oForm.frame_size.value = "Standard";
		} else {
			var sHTML = "";
			sHTML += '<table cellpadding="2" cellspacing="0" border="1" frame="below" rules="rows" width="550">';
			sHTML += '<tr>';
			sHTML += '<td width="10">&nbsp;</td>';
			sHTML += '<td width="100"><img src="/images/size_eye.gif" width="100" height="45"/></td>';
			sHTML += '<td width="100"><img src="/images/size_vertical.gif" width="100" height="45"/></td>';
			sHTML += '<td width="100"><img src="/images/size_bridge.gif" width="100" height="45"/></td>';
			sHTML += '<td width="100"><img src="/images/size_temple.gif" width="100" height="45"/></td>';
			sHTML += '<td width="100%" valign="bottom" style="font-weight: bolder; padding-left: 12px;">Price of frame</td>';
			sHTML += '</tr>';
			for (var i = 0; i < oSizes.length; i++) {
				var arr = oSizes[i].size.split("-");
				if (arr.length < 3) {
					if (arr[1] < 100)
						arr = (oSizes[i].size + "-").split("-");
					else
						arr = ("-" + oSizes[i].size).split("-");
				}
				sHTML += '<tr align="center" onmouseover="this.style.background=\'#e1e1e1\'" onmouseout="this.style.background=\'white\'"';
				if ((!oSizes[i].discontinued && (!oSizes[i].confirmed || oSizes[i].available)) || oSizes[i].instock > 0)
					sHTML += ' style="cursor: pointer;" onclick="Frame.handleSizeChange(\'' + oSizes[i].size + '\', ' + i + ', \'' + oSizes[i].upc + '\');"><td><input ';
				else
					sHTML += '><td><input disabled="disabled" ';
				sHTML += 'type="radio" value="' + oSizes[i].size + '" name="frame_size_dynamic" class="size_checkbox" id="size_checkbox_' + i + '"/></td>';
				sHTML += '<td>' + (arr[0]?arr[0] + " mm":"-") + '</td>';
				sHTML += '<td>' + (oSizes[i].size_vertical > 0?oSizes[i].size_vertical + " mm":"-") + '</td>';
				sHTML += '<td>' + (arr[1]?arr[1] + " mm":"-") + '</td>';
				sHTML += '<td>' + (arr[2]?arr[2] + " mm":"-") + '</td>';
				sHTML += '<td style="font-weight: bolder; padding-left: 12px;" align="left">';
				if (oSizes[i].instock > 0)
					sHTML += '<span style="color: red;">Only ' + oSizes[i].instock + '</span> @ <span style="color: green">' + (oSizes[i].overstock_price?formatCurrency(oSizes[i].overstock_price):formatCurrency(oSizes[i].price)) + '</span>';
				else if (oSizes[i].discontinued)
					sHTML += 'Discontinued';
				else if (oSizes[i].confirmed && !oSizes[i].available)
					sHTML += 'Sold Out';
				else if (oSizes[i].overstock_price)
					sHTML += '<span style="color: red;">Sale</span> @ <span style="color: green">' + formatCurrency(oSizes[i].overstock_price) + '</span>';
				else
					sHTML += '<span style="color: green">' + formatCurrency(oSizes[i].price) + '</span>';
				sHTML += '</td>';
				sHTML += '</tr>';
			}
			sHTML += '</table>';
			$("frame_size_area").update(sHTML);
		}

		var sSize = oForm.frame_size.value;

		var nSizeIndex = 0;
		if (oForm.frame_size_dynamic) {
			var oSize = $A(oForm.frame_size_dynamic).find(function(o) { return (o.value == sSize); });
	
			if (oSize == null)
				oSize = (oForm.frame_size_dynamic.length?oForm.frame_size_dynamic[0]:oForm.frame_size_dynamic);
	
			oSize.checked = true;
			nSizeIndex = (oForm.frame_size_dynamic.length?$A(oForm.frame_size_dynamic).indexOf(oSize):0);
			oForm.frame_size.value = oSize.value;
		}

		oForm.upc.value = oSizes[nSizeIndex].upc;

		var basePrice = oSizes[nSizeIndex].price;

		if ($("gc_value"))
			Element.update("gc_value", formatCurrency(Math.round(basePrice * oFrameInfo.gc / 100)));

		var totalPrice = parseFloat(basePrice) + extraCost;
		if ($("frame_price"))
			Element.update("frame_price", formatCurrency(totalPrice + lensCost + coatingCost + this.lens_price));
	}
}

function handleLensUsageChange(frm) {
	var flag = false;
	if (frm.usage_sport[0].checked)
		flag = true;
	if (frm.usage_child[0].checked)
		flag = true;
	
	$("lens_recommender_poly").style.display = (flag?"block":"none");
	$("lens_recommender_step2").style.display = (!flag?"block":"none");
}

function openPromo(id) {
	var url = "";
	switch(id) {
		case "plastic":
			url = "/promos/plastic/";
			break;
		case "transitions":
			url = "/promos/transitions/";
			break;
		default:
			return;
	}
	window.open(url, "", "width=660,height=830,scrollbars=1");
}