var mousePos;
var xmouse = 0;
var ymouse = 0;
var xoffset = 200;
var yoffset = 350;
var largeCaseOn = false;
var selectedCase = 'CLAMSHELL';
var t;
var firstSelected = false;
var showingOptions = false;
var shownCaseSelect = true;
var selectingLens = false;
var firstSelectedType = false;
var selectingLensType = false;
var selectingPrescription = false;
var showingPrescription = false;
var selectingNosePos = false;
var showingNosePos = false;
var selectsHidden = false;
var loadedprescription = false;

function hideSelects(theaction) {	
	if( theaction != 'visible' ){
		selectsHidden = true;
	}else{
		selectsHidden = false;
	}
	jQuery('select').toggle();
}

function proceed_button_swap(btnobj,state){
	if(state == 'over') {
		document.getElementById(btnobj).className = 'proceedButtonOver';
	} else {
		document.getElementById(btnobj).className = 'proceedButton';
	}
}

/**** START ---- STEP2 LENS TYPE AND NOSE POSITION SELECTION ****/

function selectLensType(){
	var the_form = document.orderform;
	if(the_form.mv_order_lens.length) {
		var selectedLensType = checkedVals(the_form.mv_order_lens);
	} else {
		var selectedLensType = the_form.mv_order_lens.value;	
	}

	if(selectedLensType){
		calcPrice();
		errClear();
		update_noseposition();
	
		if(!shownosepos)
			hideLensTypeSelection();
	}
}

function loadPrescription(step){
	jQuery('#prescription_data').load( '/step2_prescription.html?r=' + Math.random()*100, function(response,status){
		// This function fires once the AJAX request is finished
		// Hide the AJAX loader gif
		jQuery('#prescription_loading').hide();

		if( status == 'error' )
			jQuery('#prescription_loading').css('border','1px solid red').text('Failed to load your prescription, please try again. If you encounter this error again please contact customer service.');
	});

	loadedprescription = true;
}

function reloadNosePos(){
	var the_form = document.orderform;
	var selectedNosePos = checkedVals(the_form.mv_order_nosepos);	
	if(selectedNosePos)
		selectNosePosition();
}

function showPrescriptionBox(){
	if( (selectingLensType == false) && (showingPrescription == false) ){
		jQuery('#prescriptionbox').slideDown(700);
		selectingLensType = true;
		showingPrescription = true;
		setTimeout("window.scrollBy(0,90);",1000); //scroll the window down abit so the "step 3" button is visible
		setTimeout("selectingLensType = false;",700);	
		if( !loadedprescription ){
			//wait 1 second for animation to finish then load the prescription
			setTimeout("loadPrescription();",1000);
		}
	}
}

function hideLensTypeSelection(){
	if(selectingLensType == false){
		var the_form = document.orderform;
		if(the_form.mv_order_lens.length) {
			var selectedLensType = checkedVals(the_form.mv_order_lens);
		} else {
			var selectedLensType = the_form.mv_order_lens.value;	
		}

		try{
			var effects = new Array();
			selectingLensType = true;
			jQuery('#currentLensTypeSelectionLens').html( jQuery('#mv_order_lens_'+selectedLensType+'_label').html() );	
			
			effects.push( function(){
				jQuery('#fullLensTypeSelection').slideUp(300,function(){
					jQuery('#currentLensTypeSelection').slideDown(300);
				});
			});

			setTimeout("selectingLensType = false; showPrescriptionBox();",400);
			
			if((!selectingNosePos) && (showingNosePos)){
				if((selectedLensType.indexOf('PROG') != -1) || (selectedLensType.indexOf('PROGE') != -1) || (selectedLensType.indexOf('BIF') != -1)){
					selectingNosePos = true;
					showingNosePos = false;
					jQuery('#nosepositionbox').slideUp(300, effects.pop() );
					setTimeout("selectingNosePos = false;",300);
				}else{
					if( jQuery('#nosepositionbox').is(':visible') ){
						showingNosePos = false;
						jQuery('#nosepositionbox').slideUp(300, effects.pop() );
					}
				}
			}

			jQuery(effects).each( function(i,func){ func(); } );
		}catch(error){
			selectingLensType = false;
			setTimeout(hideLensTypeSelection,500);
			return;
		}
	}
}

var RxCommentsOn = false;

function toggleRxComments(){
	jQuery('#manualRx').toggle();
	return true;
}

function changeTypeSelection(){
	if(selectingLensType == false){
		var the_form = document.orderform;
		if(the_form.mv_order_lens.length) {
			var selectedLensType = checkedVals(the_form.mv_order_lens);
		} else {
			var selectedLensType = the_form.mv_order_lens.value;	
		}

		// Queue up the replacement of the lens type selection with the currently selected lens type
		// (This is queued so that the noseposition box is animated before if it needs to be)
		jQuery('#currentLensTypeSelection').slideUp(300, function(){
			selectingLensType = true;
			jQuery('#fullLensTypeSelection').slideDown(300, function(){ selectingLensType = false; });
		});

		if((selectedLensType.indexOf('PROG') != -1) || (selectedLensType.indexOf('PROGE') != -1) || (selectedLensType.indexOf('BIF') != -1)){
			selectingNosePos = true;
			showingNosePos = true;

			jQuery('#nosepositionbox').delay(600).slideDown(300,function(){ selectingNosePos = false; }); 
		}
	}
	return false;	
}

function selectNosePosition(){
	errClear();
	if(!selectingLensType){	
		hideLensTypeSelection();
		if(!showingPrescription){
			jQuery('#prescriptionbox').delay(1000).slideDown(700, function(){
				selectingPrescription = true;
				showingPrescription = true;
				selectingPrescription = false;
			});

			if(!loadedprescription){		
				setTimeout("loadPrescription();",1000);
			}
		}
	}	
}


/**** END ---- STEP2 LENS TYPE AND NOSE POSITION SELECTION ****/

function changeSelection(){
	if(selectingLens == false){
		jQuery('#currentLensSelection').slideUp(300,function(){
			selectingLens = true;
			jQuery('#fullLensSelection').slideDown(700, function(){ selectingLens = false; });
		});
	}
	return false;
}

function selectLensPackage(){
	errClear();
	if(selectingLens == false){
		jQuery('#fullLensSelection').slideUp(700, function(){
			selectingLens = true;
			hideLensSelection();
			selectingLens = false;
		});
	}
	return false;
}

function hideLensSelection(){
	var the_form = document.orderform;	
	var selectedLens = checkedVals(the_form.mv_order_lenstype);

	jQuery('#currentLensSelectionLens').text( jQuery('#lensLabel_' + selectedLens[0]).text() + ' - ' + jQuery('#lensLabelLink_' + selectedLens[0]).text() );
	jQuery('#currentLensSelection').slideDown(300, function(){ showCustomizeStep(); });
	jQuery('#step3buybutton').show();
}

function showCustomizeStep(){
	if( !firstSelected ){
		if(allowed_tints_count > 0){
			if(!showingOptions){
				jQuery('#lensoptions').slideDown(700);	
				showingOptions = true;
			}
			if(!shownCaseSelect){
				shownCaseSelect = true;
				setTimeout("showCaseSummaryStep()",700);
			}
		}
		else{		
			if(safety_frame > 0){	
				jQuery('#lensoptions').hide();
				showingOptions = false;
			}
			else if(!showingOptions){
				jQuery('#lensoptions').slideDown(700);
				showingOptions = true;
				if(!shownCaseSelect){
					shownCaseSelect = true;
					setTimeout("showCaseSummaryStep()",700);
				}
			}
			if(!shownCaseSelect){
				shownCaseSelect = true;
				showCaseSummaryStep();
			}
		}
	}
}

function showCaseSummaryStep(){
	jQuery('#caseSummaryContainer').slideDown(700);
}

function selectCase(selectCase){
	toggleCaseSelection();
	setTimeout("selectCaseChange('"+selectCase+"');",400);
}

function selectCaseChange(selectCase){
	var currentCaseName = document.getElementById('currentCaseName');
	var currentCasePrice = document.getElementById('currentCasePrice');
	var selectedCaseName = document.getElementById('caseName_'+selectCase);
	var currentCaseImage = document.getElementById('currentCaseImage');
	currentCaseName.innerHTML = selectedCaseName.innerHTML;
	framePrice = cost['mv_order_case'][selectCase];
	if(framePrice == 0) {
		if(locale == 'es_ES') {
			framePrice = '!Est� incluido GRATIS';
		} else {
			framePrice = 'Included FREE!';	
		}
	} else {
		framePrice = '$'+framePrice;
		if(locale == 'es_ES') {
			framePrice+= ' adicionales';
		} else {
			framePrice+= ' additional';
		}
	}
	currentCasePrice.innerHTML = framePrice;
	currentCaseImage.src = caseImages[selectCase].src;

	jQuery('#mv_order_case').val( selectCase );
	selectedCase = selectCase;
	calcPrice(); 
}

showCaseSelectionState = 0; //define case state as hidden
function toggleCaseSelection(){
	var caseLayer = document.getElementById('selectCase');
	var aleft=document.all? caseLayer.scrollLeft : caseLayer.pageXOffset
	var atop=document.all? caseLayer.scrollTop : caseLayer.pageYOffset

	caseChoose = document.getElementById('chooseCaseContainer');
	caseLayer = document.getElementById('selectCase');

	var cleft = 0;
	var ctop = 0;

	while (caseChoose.offsetParent){
		cleft += caseChoose.offsetLeft;
		ctop += caseChoose.offsetTop;
		caseChoose = caseChoose.offsetParent;
	}

	cleft += caseChoose.offsetLeft;
	ctop += caseChoose.offsetTop;

	layertop = ctop - 140;
	layerleft = cleft - 236;

	if(layertop < 0)
		layertop = 10;

	caseLayer.style.top = layertop + "px";
	caseLayer.style.left = layerleft + "px";

	if(showCaseSelectionState){
		//hide case selection
		jQuery('#selectCase').toggle(500);
		showCaseSelectionState = 0;	
	}
	else
	{
		//show case selection			
		jQuery('#selectCase').toggle(500);
		showCaseSelectionState = 1;	
	}	
}

showCasePreviewState = 0; //define case state as hidden
function previewCase(){
	var caseLayer = document.getElementById('casePreview');
	var aleft=document.all? caseLayer.scrollLeft : caseLayer.pageXOffset
	var atop=document.all? caseLayer.scrollTop : caseLayer.pageYOffset

	caseChoose = document.getElementById('chooseCaseContainer');
	caseLayer = document.getElementById('casePreview');
	
	var casePreviewImage = document.getElementById('casePreviewImage');
	casePreviewImage.src = caseLargeImages[selectedCase].src;

	var cleft = 0;
	var ctop = 0;

	while (caseChoose.offsetParent){
		cleft += caseChoose.offsetLeft;
		ctop += caseChoose.offsetTop;
		caseChoose = caseChoose.offsetParent;
	}
	
	cleft += caseChoose.offsetLeft;
	ctop += caseChoose.offsetTop;
	
	layertop = ctop - 220;
	layerleft = cleft - 200;
	
	if(layertop < 0){
		layertop = 10;
		layerleft = cleft - 600;
	}

	caseLayer.style.top = layertop + "px";
	caseLayer.style.left = layerleft + "px";
	
	if(showCasePreviewState){
		//hide case preview
		jQuery('#casePreview').toggle(500);
		showCasePreviewState = 0;	
	}
	else{
		//show case preview			
		jQuery('#casePreview').toggle(500);
		showCasePreviewState = 1;	
	}	
}






/****** START - CAPTURE MOUSE MOVEMENT AND DRAG ********/

function mouseMove(ev){
	ev = ev || window.event;
	mousePos = mouseCoords(ev);
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.documentElement.scrollLeft + document.body.scrollLeft,
		y:ev.clientY + document.documentElement.scrollTop + document.body.scrollTop
	};
}

//<![CDATA[
// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event, id) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;

  dragObj.elStartLeft  = jQuery(dragObj.elNode).position().left;
  dragObj.elStartTop   = jQuery(dragObj.elNode).position().top;

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

//]]>

/****** END - CAPTURE MOUSE MOVEMENT AND DRAG ********/



/****** START - STEP2 RX HELP QUESTIONS ********/

var rxHelpQuestion;

function toggleRxQuestion(questionNumber){
	//hide any previous element if it is not the same as the current
	if(rxHelpQuestion){
		if(rxHelpQuestion.id != 'rxQuestion'+questionNumber){
			rxHelpQuestion.style.display='none';
		}
	}
	
	//set the object to the newly select question
	rxHelpQuestion = document.getElementById('rxQuestion'+questionNumber);			
	if(rxHelpQuestion.style.display == 'block'){
		//hide this element
		rxHelpQuestion.style.display='none';		
	}
	else
	{		
		//show this element
		rxHelpQuestion.style.display='block';	
	}
}

/****** END - STEP2 RX HELP QUESTIONS ********/



/****** START - STEP2 RX HELP MOUSEOVERS ********/

var tipArray = {
	od: {
		title: 'O.D.',
		detail: 'Right eye'
	},
	os: {
		title: 'O.S.',
		detail: 'Left eye'
	},
	sph: {
		title: 'SPH (sphere)',
		detail: 'The "overall" power.  Can be minus-power or plus-power.'
	},
	cyl: {
		title: 'CYL (cylinder)',
		detail: 'The amount of astigmatism.  Can be minus-power or plus-power.<br /><br />If you have no astigmatism, sometimes doctors will write a place-holder here like "SPH" (sphere) or "D.S." (diopters sphere) to signify that there is only a sphere power needed.',
		width:300
	},
	axis: {
		title: 'AXIS',
		detail: 'Usually abbreviated with a letter "X" in front of it, this tells us the direction of the astigmatism in degrees.<br /><br />If you have no astigmatism, there will be nothing written on your prescription.  Leave it blank on our form if this is the case.',
		width:300
	},
	prism: {
		title: 'PRISM',
		detail: 'A component a doctor may add to a prescription for people with double-vision or certain special types of eyestrain.  If you see something here or a number followed by a triangle (?), type it into your order comments.  If you are still having trouble call us and we can take this order over the phone. Putting prism in your eyeglasses is an additional $19.95.',
		width:300
	},
	add: {
		title: 'ADD',
		detail: 'How much power gets added to the distance Rx for your single-vision reading-only eyeglasses OR for the bottom half of your bifocals/progressives.',
		width:300
	},
	dist: {
		title: 'DIST',
		detail: 'The distance portion of your prescription.  This is for distance eyeglasses only (or for people who do not need bifocals or progressives yet).',
		width:300
	},
	near: {
		title: 'NEAR',
		detail: 'The near (reading-only) portion of your prescription.  If it is for bifocals or progressives, sometimes the ADD power is written here.  If you are not sure, type exactly what you see in the order comments box or call us for assistance.',
		width:300
	}	
};

	
var currentObj;
var tipObj;
var tipContent;
var tipLeft;
var tipTop;

document.onmousemove = function(ev){
	mouseMove(ev);
	moveRxHelpTip();	
}

//show the rx help tips
function showRxHelpTip(item){
	//set the content
	tipContent = '<b>' + tipArray[item].title + '</b><br />' + tipArray[item].detail;
	jQuery('#tipLayer').html( tipContent );
	//Element.update('tipLayer',tipContent);
	
	tipWidth = 'auto';
	if(tipArray[item].width){
		tipWidth = tipArray[item].width + 'px';
	}
	
	tipLeft = mousePos.x + 30;
	tipTop = mousePos.y;

	jQuery('#tipLayer').css({ left: tipLeft, top: tipTop, width: tipWidth }).show();	
	//Element.setStyle('tipLayer',{display:'block',left:tipLeft + 'px',top:tipTop + 'px',width:tipWidth});
}

function moveRxHelpTip(){
	if( jQuery('#tipLayer').is(':visible') ){
		tipLeft = mousePos.x + 30;
		tipTop = mousePos.y;	
		jQuery('#tipLayer').css({ left: tipLeft, top: tipTop });		
	}
}

//hide the rx help tips
function hideRxHelpTip(){
	jQuery('#tipLayer').hide();
}


//START - FLYPAGE FORM CHECK

function checkFlypageForm() {
	jQuery('#form_error_display').hide();
	if( !jQuery('input[name=thiscolor]').is(':checked') )
		errs.push('1_nc_fc');
	if( errCheck() )
		jQuery('#orderform').submit();
}
//END - FLYPAGE FORM CHECK

//START - FLYPAGE POPUP PDF
function pdfpop() {
var URL = "nopdf.html";
var id = 46;
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=300,height=300');");
}
//END - FLYPAGE POPUP PDF

/****** END - STEP2 RX HELP MOUSEOVERS ********/

