urlAddress = "http://mropticalstage.infomaxim.com"; 
var pageName = "Mr Optical - Contacts & Glasses";
var base_cost, notDialog = false;

$.ajaxSetup({    // Disable caching of AJAX responses */    
    cache: false
});

function setValidation(prefix, activate) {
    if (activate) {
        var validateClass = $(this).attr('validation') == undefined || $(this).attr('validation') == '' ? 'validate[required]' : $(this).attr('validation');
        $('.prescription_fld.' + prefix).not('#select_qty' + prefix).addClass(validateClass);
    } else {
        $('.prescription_fld.' + prefix).not('#select_qty' + prefix).each(function() {
            var validateClass = $(this).attr('class').match(/validate\[.*\]/);
            if (validateClass != '') {
                $(this).attr('validation', validateClass);
                $(this).attr('class', $(this).attr('class').replace(validateClass, ''));
            }
        });
    }
}

// For Frames + Lenses
function AddPrescription(skipPhoto) {
	sph_right = $("#RESphere").val();
	cyl_right = $("#RECylinder").val();	
	axis_right = $("#REAxis").val();
	dist_right = $("#REDistance").val();	
	near_right= $("#RENear").val();
	right_add = $("#REAdd").val();	
	sph_left = $("#LESphere").val();
	cyl_left = $("#LECylinder").val();	
	axis_left = $("#LEAxis").val();
	dist_left = $("#LEDistance").val();	
	near_left = $("#LENear").val();
	left_add  = $("#LEAdd").val();		
	instruct = $('#instructions').val()	    	
    $('#infomaxim_analytics').load('/ajax/save_prescription.asp?GetLastImage='+skipPhoto+'&sph_right='+sph_right+'&sph_left='+sph_left+'&cyl_right='+cyl_right+'&cyl_left='+cyl_left+'&axis_right='+axis_right+'&axis_left='+axis_left+'&dist_right='+dist_right+'&dist_left='+dist_left+'&near_right='+near_right+'&near_left='+near_left+'&right_add='+right_add+'&left_add='+left_add+'&instruct='+URLEncode(instruct),
        function(){
		    CheckOut();
	});
}

// Contact Lenses
function AddLensPrescription(side) {
	qty_right = $("#select_qtyRE").val();
	qty_left = $("#select_qtyLE").val();
	sph_right = $("#RE_Sphere").val();
	base_right = $("#select_Base_CurveRE").val();
	diam_right = $("#select_DiameterRE").val();
	cyl_right = $("#RE_Cylinder").val();	
	axis_right = $("#RE_Axis").val();
	dist_right = $("#REDistance").val();	
	near_right= $("#RENear").val();
	right_add = $("#RE_Add").val();	
	sph_left = $("#LE_Sphere").val();
	base_left = $("#select_Base_CurveLE").val();
	diam_left = $("#select_DiameterLE").val();
	cyl_left = $("#LE_Cylinder").val();	
	axis_left = $("#LE_Axis").val();
	dist_left = $("#LEDistance").val();	
	near_left = $("#LENear").val();
	left_add  = $("#LE_Add").val();	
	
	//Colours
	colour_left = ''	
	$("[id^='le_colour']").each(function(index) {		
		colour_id_meta = $(this).attr('id');
		colour_id_array = colour_id_meta.split('_');
		colour_id = colour_id_array[2];
		if ($(this).val().length != 0) {
			if (colour_left.length > 0) {colour_left = colour_left +','};
			colour_left = colour_left + colour_id + ',' + $(this).val()	;	
		}	
	}); 	
	colour_right = '' 
	$("[id^='re_colour']").each(function(index) {		
		colour_id_meta = $(this).attr('id');
		colour_id_array = colour_id_meta.split('_');
		colour_id = colour_id_array[2];
		if ($(this).val().length != 0) {
			if (colour_right.length > 0) {colour_right = colour_right +','};
			colour_right = colour_right + colour_id + ',' + $(this).val()	;
		}
    });

    if (side == 'right') {
        $('#infomaxim_analytics').load('/ajax/save_prescription.asp?colour_right=' + colour_right + '&diam_right=' + diam_right + '&base_right=' + base_right + '&qty_right=' + qty_right + '&sph_right=' + sph_right + '&cyl_right=' + cyl_right + '&axis_right=' + axis_right + '&dist_right=' + dist_right + '&near_right=' + near_right + '&right_add=' + right_add);
    } else if (side == 'left') {
        $('#infomaxim_analytics').load('/ajax/save_prescription.asp?colour_left=' + colour_left + '&diam_left=' + diam_left + '&base_left=' + base_left + '&qty_left=' + qty_left + '&sph_left=' + sph_left + '&cyl_left=' + cyl_left + '&axis_left=' + axis_left + '&dist_left=' + dist_left + '&near_left=' + near_left + '&left_add=' + left_add,
        function() {
            CheckOut();
        });
    } else {
        $('#infomaxim_analytics').load('/ajax/save_prescription.asp?colour_left=' + colour_left + '&colour_right=' + colour_right + '&diam_left=' + diam_left + '&diam_right=' + diam_right + '&base_right=' + base_right + '&base_left=' + base_left + '&qty_right=' + qty_right + '&qty_left=' + qty_left + '&sph_right=' + sph_right + '&sph_left=' + sph_left + '&cyl_right=' + cyl_right + '&cyl_left=' + cyl_left + '&axis_right=' + axis_right + '&axis_left=' + axis_left + '&dist_right=' + dist_right + '&dist_left=' + dist_left + '&near_right=' + near_right + '&near_left=' + near_left + '&right_add=' + right_add + '&left_add=' + left_add,
        function() {
            CheckOut();
        });
    }
}

function AddLensesToCart(price, product, VariantID, GST) {

    //******************Validation************************
    $(".formError").remove();
    
    var validated = true;
    if (!$('#willEmail').is(':checked')) { // validate only if prescription not will be emailed
        //check if are colours still unassigned & validation
        if ($('.select_colour.re').length > 0 && stillRemainColours()) {
            validated = false;
            $('#coloursTitle').validationEngine('showPrompt', 'Please ensure Right/Left Eye Colour Qty = Right/Left Eye Qty Selected.');
        } else {
            $('.coloursTitleformError').fadeOut(150, function() {$(this).remove();});
        }

        if (!$("#dialogForm").validationEngine('validate')) validated = false;
    }
    //****************************************************

    if (validated) {
		//If there are power selects visibles, QTYs of LE and RE are > 0 then need to add to cart LE/RE separately
		if ( ( ( ($('.power_select.LE').val() == 0)&&($('.power_select.RE').val() != 0) )||( ($('.power_select.RE').val() == 0)&&($('.power_select.LE').val() != 0) ) ) && (($('#select_qtyLE').val() > 0) && ($('#select_qtyRE').val() > 0))) {
			$.ajaxSetup({async: false});
			//******Add to cart RE*******
			Qty = $('#select_qtyRE').val(); 
			GST = '0';
			//$('.power_select.RE').each(function(){
				if ( parseInt($('.power_select.RE').val()) == 0) {
					GST = '1';
				}
			//});
			
			LensArray = $('#variant_select').val().split('_');
			$('#toptabs').load('/views/cart.asp?Product_Title='+URLEncode(ProductTitle)+'&price='+LensArray[2]+'&GST='+GST+'&ProductTable=spec_lenses&variant_id=' + LensArray[1] + '&product=' + product + '&action=add&IsPack=1&price=&qty='+Qty,
			function() {
				AddLensPrescription('right');
			});

			//******END - Add to cart RE*******
			
			//******Add to cart LE*******
			Qty = $('#select_qtyLE').val(); 
			GST = '0';
			//$('.power_select.LE').each(function(){
				if ( parseInt($('.power_select.LE').val()) == 0) {
					GST = '1';
				}
			//});
			
			$('#toptabs').load('/views/cart.asp?Product_Title='+URLEncode(ProductTitle)+'&price='+LensArray[2]+'&GST='+GST+'&ProductTable=spec_lenses&variant_id=' + LensArray[1] + '&product=' + product + '&action=add&IsPack=1&price=&qty='+Qty,
			function() {
				AddLensPrescription('left');
			});
			//******END - Add to cart LE*******
			$.ajaxSetup({async: true});
			
		} else {


            Qty = totalQty //QtyElement.options[selIndex].value;
            
            //check if needed to add GST or not
            GST = '1';
            if ($('#select_qtyLE').val() > 0) {
                $('.power_select.LE').each(function () {
                    if (parseFloat($(this).val()) != 0) {
                        GST = '0';
                    }
                });
            } else {
                $('.power_select.RE').each(function () {
                    if (parseFloat($(this).val()) != 0) {
                        GST = '0';
                    }
                });
            }

			LensArray = $('#variant_select').val().split('_');
			$('#toptabs').load('/views/cart.asp?Product_Title='+URLEncode(ProductTitle)+'&price='+LensArray[2]+'&GST='+GST+'&ProductTable=spec_lenses&variant_id=' + LensArray[1] + '&product=' + product + '&action=add&IsPack=1&price=&qty='+Qty,
			function() {
				AddLensPrescription();
			});
		}

    } else {
        //$("#dialogForm").validationEngine({ validationEventTrigger: 'blur' })
    }
}

function CheckOut() {
    var protocol = 'http'
    url = location.href
    var matchPos1 = url.indexOf('www');
    //alert(string1);
    if (matchPos1 != -1) {
        protocol = 'https'
    }
    else {
        protocol = 'http'
    }
    //alert(matchPos1+':'+protocol);
    location.href = protocol + '://' + location.hostname + '/checkout.asp'
}

function addToFavorites() { 
	if (window.external) { 
		window.external.AddFavorite(urlAddress,pageName);
		alert('Bookmark added'); 
	} else { 
		alert("Sorry! Your browser doesn't support this function."); 
	} 
}


function updateRemainLE() {
    var totalLE = 0
    $('.select_colour.le').each(function() {

        //add only if the value is number
        var val = $(this).val();
        if (!isNaN(val) && val.length != 0) {
            totalLE += parseInt(val);
        }
    });
    totalRemainLE = parseInt(parseFloat($('#select_qtyLE').val())) - totalLE
    $("#span_remainLE").html('(' + totalRemainLE + ' remain)');
}

function updateRemainRE() {
    var totalRE = 0
    $('.select_colour.re').each(function() {

        //add only if the value is number
        var val = $(this).val();
        if (!isNaN(val) && val.length != 0) {
            totalRE += parseInt(val);
        }
    });
    totalRemainRE = parseInt(parseFloat($('#select_qtyRE').val())) - totalRE
    $("#span_remainRE").html('(' + totalRemainRE + ' remain)');
}

function updateLQty() {
    var totalRE = 0, totalRE = 0
    
    var val = $('#select_qtyRE').val();
    if (!isNaN(val) && val.length != 0) {
    	totalRE = parseInt(val);
    }

    /*var val = $('#select_qtyLE').val();
    if (!isNaN(val) && val.length != 0) {
        totalLE = parseInt(val);
    }*/

    /* if ((totalLE + totalRE) > totalQty) {
        var newQty = '';
        $($('#variant_select')[0].options).each(function() {
            if (parseInt($(this).attr('title')) >= (totalLE + totalRE) && newQty == '') {
                newQty = this.value;
                totalQty = parseInt($(this).attr('title'));
                $('#variant_select').val(newQty)
            }
        });
    } */
        
    $("#select_qtyLE").val(totalQty - totalRE);
    updateRemainLE();
    updateRemainRE();
}

function updateRQty() {
    var totalLE = 0, totalRE = 0
    var val = $('#select_qtyLE').val();
    if (!isNaN(val) && val.length != 0) {
    	totalLE = parseInt(val);
    }
    
    /*var val = $('#select_qtyRE').val();
    if (!isNaN(val) && val.length != 0) {
    	totalRE = parseInt(val);
    }*/


    /*if ((totalLE + totalRE) > totalQty) {
        var newQty = '';
        $($('#variant_select')[0].options).each(function() {
            if (parseInt($(this).attr('title')) >= (totalLE + totalRE) && newQty == '') {
                newQty = this.value;
                totalQty = parseInt($(this).attr('title'));
                $('#variant_select').val(newQty)
            }
        });
    } */ 

    $("#select_qtyRE").val(totalQty - totalLE);
    updateRemainLE();
    updateRemainRE();

}

function SetDefaults() {
    //all selects in dialog with only one value should be selected by default
    $('#contacts select').each(function() {
        if (this.children.length > 0) { $(this).val(this.children[0].value) }
    });
    dialogUpdate();
	$('.select_colour').change(function() {
        if ($(this).hasClass('le')) {
            updateRemainLE();
        } else {
            updateRemainRE();
        }
    });

    /*$('#select_qtyRE').change(function() {
        updateRemainRE();
        if ($(this).val() == '0' || $(this).val() == '') { setValidation('RE', false) } else { setValidation('RE', true) };
        //updateLQty();
    });
    $('#select_qtyLE').change(function() {
        updateRemainLE();
        if ($(this).val() == '0' || $(this).val() == '') { setValidation('LE', false) } else { setValidation('LE', true) };
        //updateRQty();
    });*/

}

function updateValidators() {
    var qtySelect = $("#select_qtyRE")
    if (qtySelect.val() == '0' || qtySelect.val() == '') { setValidation('RE', false) } else { setValidation('RE', true) };
    var qtySelect = $("#select_qtyLE")
    if (qtySelect.val() == '0' || qtySelect.val() == '') { setValidation('LE', false) } else { setValidation('LE', true) };
}

function ClearContactForm() {
    SetDefaults();
    //Set fields to pick
    $("#Sphere").val('Pick');
}

function dialogUpdate() {
    $('#select_qtyRE').val(totalQty / 2);
    $('#select_qtyLE').val(totalQty / 2);
    if (totalQty == 1) {
        $('#select_qtyRE').val('1');
        $('#select_qtyLE').val('0');
    }

    $('.select_colour').val('')

    updateRemainRE();
    updateRemainLE();
}


$(function() {


    //change the default value of search text field 
    $('.defValue').each(function() {
        var default_value = this.value;
        $(this).focus(function() {
            if (this.value == default_value) {
                this.value = '';
            }
        });
        $(this).blur(function() {
            if (this.value == '') {
                this.value = default_value;
            }
        });
    });

    // jQuery UI modal box
    $('#dialog').dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        close: function() { $("#dialogForm").validationEngine('hideAll'); },
        width: 724,
        autoResize: true
    });



    $('.cart').not('.fromDialog').click(function() {
        $('#sub_total').val(base_cost);

        if (notDialog) {
            SimpleAddOrderToCart();
        } else {
            $('#variant_select').val($(this).attr('id'));
            $('input[name="lens_type"]').attr('checked', false);
            $("#lensType").css("display", "none");
            $("#options").css("display", "none");
            $("#tint").css("display", "none");
            //$('#sub_total').val(base_cost);	
            $("#prescription").css("display", "none");
            $('#prescription').load('/ajax/prescription.asp?t=');
            totalQty = parseInt($(this).attr('units'));
            dialogUpdate();

            $('#variant_select').change(function() {
                totalQty = parseInt($('#variant_select :selected').attr('title'));
                dialogUpdate();
                updateValidators();
            });

            updateValidators();

            $("#select_qtyRE, #select_qtyLE").change(function() {
                $("#dialogForm").validationEngine('validateField', '#select_qtyRE');
                var prefix = $(this).hasClass('LE') ? 'LE' : 'RE';
                $(".prescription_fld." + prefix).not('#select_qty' + prefix).each(function() { $('.' + this.id + 'formError').remove(); $("#dialogForm").validationEngine('validateField', '#' + this.id); })

                $("#dialogForm").validationEngine('validateField', '#select_qtyRE');

                eval('updateRemain' + prefix + '();');

                updateValidators();
            });

            $('.select_colour').change(function() {
                if (stillRemainColours()) {
                    $('#coloursTitle').validationEngine('showPrompt', 'Please ensure Right/Left Eye Colour Qty = Right/Left Eye Qty Selected.');
                } else {
                    $('.coloursTitleformError').fadeOut(150, function() { $(this).remove(); });
                }
            });

            if ($.browser.safari == true) {
                // disable modal mode
                $("#dialog").dialog('option', 'modal', false);

                // show overlay div manually
                var tempDiv = $("<div id='tempOverlayDiv'></div>");
                tempDiv.css("background-color", "#000");
                tempDiv.css("opacity", "0.2");
                tempDiv.css("position", "absolute");
                tempDiv.css("left", 0);
                tempDiv.css("top", 0);
                tempDiv.css("width", $(document).width());
                tempDiv.css("height", $(document).height());
                $("body").append(tempDiv);

                // remove overlay div on dialog close
                $("#dialog").bind('dialogclose', function(event, ui) {
                    $("#tempOverlayDiv").remove();
                });

            }

            $('#dialog').dialog('open');
            
            $("#dialogForm").validationEngine({ validationEventTrigger: 'blur' })
        }
    });

    $('.closeDialog').click(function() {
        $('#dialog').dialog('close');
        return false;
    });

    $('#lcClose').click(function() {
        $('#lens_shape_chooser').dialog('close');
        return false;
    });

    $('.choose_lens_shape').click(function() {
        $('.lens_shape_chooseformError').fadeOut(150, function() { $(this).remove(); });
        //if ($('#lens_shape_image').attr('src')!='') $('#'+$('#lens_shape_image').attr('src').replace('/assets/images/','')).attr('selected','selected');
        if ($.browser.safari == true) {
            $('#lens_shape_chooser').dialog('option', 'modal', false);
            // show overlay div manually
            var tempDiv = $("<div id='tempOverlayDiv'></div>");
            tempDiv.css("background-color", "#000");
            tempDiv.css("opacity", "0.2");
            tempDiv.css("position", "absolute");
            tempDiv.css("left", 0);
            tempDiv.css("top", 0);
            tempDiv.css("width", $(document).width());
            tempDiv.css("height", $(document).height());

            $("#lens_shape_chooser").bind('dialogclose', function(event, ui) {
                $("#tempOverlayDiv").remove();
            });

            $("body").append(tempDiv);

        }

        $('#lens_shape_chooser').dialog('open');
    });

    $('#willEmail').change(function() {
        var checked = $(this).is(':checked');
        $(".prescription_fld").attr('disabled', checked ? 'disabled' : '');
        $(".formError").remove();
    });

    //assign ids
    $('.helpLink').each(function(i) {

        var helpBtnId = 'helpBtn' + i;
        var helpDialogId = 'helpDialog' + i;
        var closeHelpId = 'closeHelp' + i;

        $(this).attr('id', helpBtnId).children('span.helpDialog').attr('id', helpDialogId).children('span.helpClose').attr('id', closeHelpId);

    });

    $('[id^=helpDialog]').dialog({
        modal: true,
        autoOpen: false,
        //width: 380,
        //height: 450,
        resizable: false,
        position: 'center'
    });

    //get help btn number user clicked on and show appr. help info
    $('.helpLink').click(function() {
        //strip off prefix of button id to get number for dialog
        var helpBtnIdPrefix = 'helpBtn';
        var helpBtnNum = $(this).attr('id').substring((helpBtnIdPrefix.length));

        //offset returns top and left of element
        var helpBtnOffset = $('#helpBtn' + helpBtnNum).offset();
        //width of element
        var helpBtnWidth = $('#helpBtn' + helpBtnNum).width();
        //width of dialog box
        var dialogWidth = $('#helpDialog' + helpBtnNum).dialog('option', 'width');

        //x and y positions of dialog box
        //x position: add btn width and subtract dialog width from btn left offset
        //y postion: subtract window top postion from btn top offset if user scrolled

        var position = [$('#' + helpBtnIdPrefix + helpBtnNum).offset().left + $('#' + helpBtnIdPrefix + helpBtnNum).outerWidth() + 5, $('#' + helpBtnIdPrefix + helpBtnNum).offset().top - $(document).scrollTop() + 15];

        $('#helpDialog' + helpBtnNum).dialog('option', 'position', position);
        $('#helpDialog' + helpBtnNum).dialog('open');

        return false;
    });

    //added close btn at bottom of dialog
    $('[id^=closeHelp]').click(function() {
        var closeHelpPrefix = 'closeHelp';
        var closeHelpNum = $(this).attr('id').substring((closeHelpPrefix.length));
        $('#helpDialog' + closeHelpNum).dialog('close');
    });

    return false;


});

function checkQTY(field, rules, i, options) {
    if (parseInt(parseFloat("0"+$('#select_qtyRE').val())) + parseInt(parseFloat("0"+$('#select_qtyLE').val())) != totalQty) {
        // this allows the use of i18 for the error msgs
        return "Please ensure Right Eye Qty + Left Eye Qty = Total Boxes selected.";
    }
}

function stillRemainColours() {
    var retval = false;
    if ((totalRemainRE != 0) || (totalRemainLE != 0)) {
        retval = true;
    }
    return retval;
}

function validatePD() {
    if ($('#REDistance').val() == '' && $('#LEDistance').val() == '' && ($('#LENear').val() == '' || $('#LENear').length==0) && ($('#RENear').val() == '' || $('#RENear').length==0)) {
        if ($('#RENear').length != 0)
            $('#RENear').validationEngine('showPrompt', 'Please select at least 1 of 4 PD selects.');
        else
            $('#REDistance').validationEngine('showPrompt', 'Please select at least 1 of 2 PD selects.');
        return false;
    } else {
        $('.RENearformError').fadeOut(150, function() {
            // remove prompt once invisible
            $(this).remove();
        });
        $('.REDistanceformError').fadeOut(150, function() {
            // remove prompt once invisible
            $(this).remove();
        });
        
        return true;
    }
}

function removeClassByPrefix(el, prefix) {
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
    el.className = el.className.replace(regx, '');
    return el;
}

function SubmitImage() {
	if ($('#file_name').val()!='') {
		var options = {
			url: '/ajax/save_frame_photo.asp?debugon=1',
			target: '#infomaxim_analytics',
			success: function() { 
				photoUploaded = true;
				$('#image_upload').dialog('close');
				AddOrderToCart('');    
			}
		};

		//TODO - show an ajax spinner
		$('#errorMsg').fadeOut();
		$('#uploading').fadeIn();
		$('#image_upload_form').ajaxSubmit(options);
	} else {
		$('#errorMsg').fadeIn();
		setTimeout(function(){$('#errorMsg').fadeOut();},2000)
	}
}

