﻿var lastColorChoice = '';
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;

//Represents the state of common page level variables
function PageState(){
    this.__type = 'Orvis.ProductPage.ProductPageState';
    this.pfid = '';
    this.prodGroupID = '';
    this.imagePath = '';
    this.currentChoiceValues = null; 
}

//Represents the current choice value selections
function CurrentChoiceValues(){
    this.__type = 'Orvis.ProductPage.CurrentChoiceValues';
    this.ChoiceValue1 = '';
    this.ChoiceValue2 = '';
    this.ChoiceValue3 = '';
    this.ChoiceValue4 = '';
}

//Opens a new browser window and sets focus
function ShowNewWindow(height, width, url)
{ 
	newWindow = window.open(url, 'OrvisHelpWindow_', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=1,copyhistory=0, left=1, top=1,width=' + width + ',height=' + height);
	if(newWindow){
	    newWindow.focus();
	}
}


//Swatch and Choice functions
//******************************************

var imagePath = ''; // global variable that stores the current image path, for caching.  Use SetImagePath('http://images2.orvis.com') in the
                    // page to set the value.
                    
function SetImagePath(newPath) { imagePath = newPath; }
                    
function ChangeImg(cImage,cColor)
   {
	     //Guard so this doesn't fail when RichFX is in place instead of the main image
	    if($('colorset'))
	    {
	        if(cImage != ""){
		        $('colorset').src = imagePath + "/orvis_assets/prodimg/" + cImage;
		        $('hdnCurrentColorChoice').value = cImage;
		    } 
		    $('hdnCurrentColorName').value = cColor;
		}
   }

function ChangeColorFromDropDown(dropDownName, changeOption){
    ChangeColor($F(dropDownName), false);
}

function ChangeColorFromBasketLoad(imageName, colorValue){
    lastColorChoice = colorValue;  //Save off the last color
    if(imageName != ''){
        if($('colorset'))
	    {
		    $('colorset').src = imagePath + "/orvis_assets/prodimg/" + imageName;
		}
   } 
}


//Swaps the current main product image with one represented by the swatch
function ChangeColor(cColor, changeOption)
{
    HideRichFX()
    //Save off the last color choice
    lastColorChoice = cColor;
    
	for(x=0;x<colorArray.length;x++)
	{
		if (colorArray[x][0] == cColor.toUpperCase()) 
		{
			ChangeImg(colorArray[x][1],colorArray[x][0]);
			if(changeOption){
			    ChangeOption(colorArray[x][0]);
			} 
			break;
		}
	}
}

//Changes color drop downs when a swatch is clicked
function ChangeOption(swatchColor){    
    var colorChoiceDropDownName = '';
    var colorChoiceDropDown = null; 
    
    //Check to see if there was a "color" or "type" drop down set by the server side code as a hidden element
   //if so, grab the value 
   if($('hdnColorChoiceDropDown')){
        colorChoiceDropDownName = $F('hdnColorChoiceDropDown');
   
        //Set the drop down if it exists, has more than the default option, and has the color as an option
        if($(colorChoiceDropDownName)){
            colorChoiceDropDown = $(colorChoiceDropDownName);  
            if( ($A(colorChoiceDropDown.options).size() > 1) && ($A(colorChoiceDropDown.options).pluck('value').indexOf(swatchColor) != -1) ){
                colorChoiceDropDown.selectedIndex = $A(colorChoiceDropDown.options).pluck('value').indexOf(swatchColor);
               //If there are more choices after this one, you will need to fire the onchange is code as it will not fire
                if(colorChoiceDropDown.onchange){
                    colorChoiceDropDown.onchange();
              } 
            } 
        }
    }
}

//Validates the choices and quantity for the product page
function Validate(){
    var isSelectValid = true;
    var selectError = 'Please select all Options for the item.';
    var quantityError = 'Please select a quantity greater than 0'; 
    //Check any available choices
    for(var i = 1; i <= 4; i++){
        if($('selChoice-' + i)){
            if($F('selChoice-' + i) == -1){
                isSelectValid = false; 
            }
        } 
    } 
    //a choice is invalid 
    if(!isSelectValid){
        alert(selectError);
        return false; 
   //check for quantity less than 0
   }else if($('txtQuantity') && $F('txtQuantity') < 1){
        alert(quantityError);
        return false;
   }else{
    return true;
   }
}

//Creates the HTML for a drop down list from the JSON returned from the server
function BuildDropDownHTML(choiceValues, dropDownID, choiceIndex, choiceCount){
    var defaultOptionText = defaultDropDownText;
    var dropDownName = 'selChoice-' + dropDownID;
    
    var dropDownString = '<select name="' + dropDownName + '" id="' + dropDownName + '"';
   
    if(choiceIndex < choiceCount){
        dropDownString += ' onchange="GetNextChoices(' + dropDownID + ',' +  (choiceIndex + 1) + ',' + choiceCount + ');"'; 
        if($('hdnColorChoiceDropDown') && $('hdnColorChoiceDropDown').value == dropDownName){
            dropDownString += 'ChangeColorFromDropDown(\'' + dropDownName + '\', false);';
        }
    }  
    else{ 
        if($('hdnColorChoiceDropDown') && $('hdnColorChoiceDropDown').value == dropDownName){
            dropDownString += ' onchange="ChangeColorFromDropDown(\'' + dropDownName + '\', false);"';
      }
    
   }  
  
   //Close the select list
   dropDownString += '>';
   
   if(choiceValues.length > 0){ 
        dropDownString += '<option value="-1">' + defaultOptionText + '</option>';
        $A(choiceValues).each(function(s){
            if(s.Value == lastColorChoice){
                dropDownString += '<option value="' + s.Value + '" SELECTED>' + s.Text + '</option>';
            }else{
                dropDownString += '<option value="' + s.Value + '">' + s.Text + '</option>';
            }
        });  
   }else{
        dropDownString += '<option value="-1">' + defaultOptionText + '</option>';
   }
   
   dropDownString += '</select>';
   
   return dropDownString;
}

function GetNextChoices(dropDownID, choiceIndex, choiceCount){
    var selectedChoiceValue = $F('selChoice-' + dropDownID);
    pageState.currentChoiceValues['ChoiceValue' + dropDownID] =  selectedChoiceValue;
   
    var loadingMessage = 'loading...';

    //Get the div container for the next choice
    var choiceDiv = $('choiceDiv' + (dropDownID + 1) );
    if(choiceDiv){ 
        choiceDiv.innerHTML = choiceDiv.innerHTML.replace(defaultDropDownText, loadingMessage);
         
        CallJSONService('/services/ProductPageService.asmx', 'GetChoiceValues',  {myState: pageState, myCurrentChoiceValues: pageState.currentChoiceValues, choiceIndex: dropDownID}, function (value){
                    choiceData = value;
                    //Build html select and the hook for NEXT choice
                    choiceDiv.innerHTML = BuildDropDownHTML(choiceData, dropDownID + 1, choiceIndex + 1, choiceCount);
                    ResetSubsequentChoices(choiceIndex, choiceCount);
                    
            });   
        }
}

//Set any choices back to the default if they are 1 part the next one.  For example, with 3 choices, if the user changes
//choice 1, 2 will get the real values, but 3 will now need to be reset to default until the user chooses 4
function ResetSubsequentChoices(choiceIndex, choiceCount){
    var myChoiceIndex = choiceIndex;
    while(myChoiceIndex < 4){
        var choiceDiv = $('choiceDiv' + (myChoiceIndex + 2));
        if(choiceDiv){
            choiceDiv.innerHTML = BuildDropDownHTML(new Array(), myChoiceIndex + 2, myChoiceIndex + 2, choiceCount);
        }
            myChoiceIndex++;
    } 
}

// do css mouseovers on unconnected elements
function highlightLink(linkName, color){
    var sl = $(linkName);
    if (sl) {
        if (color == 'red') {
            sl.className = 'ActionLinkRed';
        } else {
            sl.className = 'ActionLink';
        } 
    }
 }
 
 // do freeform css mouseovers on unconnected elements
 function highlightLinkText(linkName, cssClass){
    var sl = $(linkName);
    if (sl) {
        sl.className = cssClass;
    }
 }

// Send to a Friend
var EmailControl = function(inputRName, inputREmail, inputSName, inputSEmail, inputPMessage, pfName, pfURL, divDisplay, btnSubmit, btnCancel, btnTrigger) {
    this.rName = $(inputRName); this.rEmail = $(inputREmail);
    this.sName = $(inputSName); this.sEmail = $(inputSEmail);
    this.pMessage = $(inputPMessage);
    this.display = $(divDisplay);
    this.submit = $(btnSubmit);
    this.cancel_button = $(btnCancel);
    this.trigger = $(btnTrigger);
    this.pf_name = pfName; this.url = pfURL;

    this.toggle = function(e) { if (this.display) { 
            if (this.display.visible()) { this.display.hide(); } else { this.display.show(); }
            if (e) { e.stop(); }
        }};
    
    this.handleResponse = function(emailResponse) {
        emailResponse = eval('(' + emailResponse + ')');
        if (emailResponse.Status != "Success") {
            this.display.toggle();
        }
        alert(emailResponse.Message);
    }
    this.sendEmail = function() {
        this.toggle();
        var msg = { ToName:this.rName.value, ToEmail:this.rEmail.value,
                    FromName:this.sName.value, FromEmail:this.sEmail.value,
                    Message:this.pMessage.value, PFName:this.pf_name, URL:this.url + '&adv=1130' };
        //alert(Object.toJSON(msg));
        CallPageService('/ServicePages/EmailService.aspx', 'SendProductEmail', [msg], this.handleResponse.bindAsEventListener(this), FailedCallback, 'JSON');
    };
    
    if (this.trigger) {
        Event.observe(this.trigger, "click", this.toggle.bindAsEventListener(this));
        if (this.display) { this.display.hide(); }        
    }
    
    if (this.submit) {
        Event.observe(this.submit, "click", this.sendEmail.bindAsEventListener(this));
    }
    
    if (this.cancel_button) {
        Event.observe(this.cancel_button, "click", this.toggle.bindAsEventListener(this));
    }
    
} 

function ChangeImage(colorValue) { var s;
    if (s = PFSwatches.find(function(i) { return (i.item_color == colorValue); })) {
        HideRichFX();
        MainPFImage.src = s.src;
    }
}

function ShowFlashObject() {
    var i;
    if (i = $('withFlash')) {
    //if (i = $('withRichFX')) {        
        if (Prototype.Browser.IE6) { i.hide(); }
        else { i.addClassName("showUnderFlash"); i.removeClassName("showOverFlash"); }
        //else { i.addClassName("showUnderRichFX"); i.removeClassName("showOverRichFX"); }        
    }
}
function HideFlashObject() {
    var i;
    if (i = $('withFlash')) { 
    //if (i = $('withRichFX')) { 
        if (Prototype.Browser.IE6) { i.show(); }
        else { i.addClassName("showOverFlash"); i.removeClassName("showUnderFlash"); }
        //else { i.addClassName("showOverRichFX"); i.removeClassName("showUnderRichFX"); }

        HideHeroVideo();
    }
}

function ShowRichFX() { return ShowFlashObject(); }
function HideRichFX() { return HideFlashObject(); }

function HideHeroVideo() {
    if (typeof(flash_HeroShotVideo) == 'undefined') { return; }
    if (check(flash_HeroShotVideo.isPaused) && check(flash_HeroShotVideo.playPause)) {
        if (!flash_HeroShotVideo.isPaused()) { flash_HeroShotVideo.playPause(); }
    }
    //return HideFlashObject();
}

function ShowHeroVideo(moviename) {
    flashVars_HeroShotVideo.movieName = moviename;
    if (flash_HeroShotVideo.canPlay()) {
        flash_HeroShotVideo.changeMovie(moviename, flashVars_HeroShotVideo);
    } else {
        flash_HeroShotVideo.changePlayer( 
            flashFile_HeroShotVideo,
            flashVars_HeroShotVideo 
        );
    }
    return ShowFlashObject();   
}
