﻿var DEFAULTFRAME = 602;  // default frame
var DEFAULTMAT = 1324; // default mat
var DEFAULTGLAZING = 4; // default glazing
var DEFAULTPAPER = 1; // default paper

// these variables should get set for each piece on frameshop load
var museum;
var imid = 0;   // image id
var frame_thumb_selected = 0;  // selected frame
var paper_thumb_selected = 0; // selected paper;
var mat_thumb_selected = 0; // selected mat

// *** MATS ***
var currentMatTab = 1;
var topMatName = "";
var middleMatName = "";
var bottomMatName = "";
var infoClicked = false;

var mat_top=3.0;
var mat_bottom=3.0;
var mat_left=3.0;
var mat_right=3.0;

// add to cart
function AddToCart() {
    if (configurationIsValid) {
        var url = $('urlAddToCart').value;
        if ((url.toLowerCase().indexOf('scid=') >=0) || (url.toLowerCase().indexOf('.aspx?') >=0))
                url += "&" + GetPricingQueryString();
        else 
            url += "?" + GetPricingQueryString();
            
        // Damian Murphy 2009.6.1
        // Just wanted to call out the hard-coded page reference. 
        if (url.indexOf("EditFrames.aspx") > 0)
            url += "&mode=selected";
            
        window.location = url; 
    } else {
        alert("This configuration is not valid, please see the error in red and fix before adding to cart.");
    }
}

// *** CANVAS ***
function updateCanvas() 
{
	calculateMaterialId();
	ServerRefresh();
}

// mat sizing popup
function EnableMatSizing() {
    if ($('numMats') == 0) {
        alert("You must have at least one mat.");
        return;
    } 

    // Fix for IE bug, hide all dropdowns
    var dd = document.getElementsByTagName("select");
    for (i=0; i < dd.length; i++) {
        dd[i].style.visibility = "hidden";
    }
    
    // Show the divs
    $("mat_sizing_content").style.display = "block";
    //$("mat_sizing_new").style.display = "block";
    //$("mat_sizing_new").style.visibility = "block";
    
    // Calculate widths and dpis
    var bucketWidth = 400;
    var bucketHeight = 450;
    var outerWidth = printWidth;
    var outerHeight = printHeight;
    var maxMatWidth = 0.25 + 0.25 + 9.0;
    var margin = Number(maxMatWidth) + Number(frameWidth);
    outerWidth = Number(outerWidth) + (2 * Number(margin));
    outerHeight = Number(outerHeight) + (2 * Number(margin));
    var dpiX = bucketWidth / outerWidth;
    var dpiY = bucketHeight / outerHeight;
    matSizingDpi = (dpiX < dpiY) ? dpiX : dpiY;
    var frameWidthPx = Math.ceil(matSizingDpi * frameWidth);
    var frameId = $("frameID").value;
    // Update frame piece URLs
    $("tdLeft").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=6) bottom left repeat-y";
    $("tdLeft").width = frameWidthPx ;
    $("tdtopLeft").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=6) bottom left repeat-y";
    $("tdtopLeft").width = frameWidthPx ;
   
    $("tdRight").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=2) bottom right repeat-y";
    $("tdRight").width = frameWidthPx ;
    $("tdbottomRight").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=2) bottom right repeat-y";
    $("tdbottomRight").height = frameWidthPx ;
       
    $("tdtop").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=0) top left repeat-x";
    $("tdtop").height = frameWidthPx ;
    $("tdtopRight").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=0) top left repeat-x";
    $("tdtopRight").width = frameWidthPx ;
    

    $("tdbottom").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=4) bottom left repeat-x";
    $("tdbottom").height = frameWidthPx ;
    $("tdbottomLeft").style.background = "url(services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=4) bottom left repeat-x";
    $("tdbottomLeft").height = frameWidthPx ;

    $("imgtopRight").src = "services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=1 ";
    $("imgtopRight").height = frameWidthPx ; 
    $("imgtopRight").width = frameWidthPx ; 

    $("imgbottomRight").src = "services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=3 ";
    $("imgbottomRight").height = frameWidthPx ; 
    $("imgbottomRight").width = frameWidthPx ;
    
    $("imgbottomLeft").src = "services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=5 ";
    $("imgbottomLeft").height = frameWidthPx ; 
    $("imgbottomLeft").width = frameWidthPx ;

    $("imgtopLeft").src = "services/frame_piece.ashx?frameId=" + frameId + "&widthPx=" + frameWidthPx + "&pieceEnum=7 ";
    $("imgtopLeft").height = frameWidthPx ; 
    $("imgtopLeft").width = frameWidthPx ;   
    
    // Update the artwork rendering (use all parameters except top mat and frame
    var matSizingImageUrl = "/services/frame_engine.ashx?IMID=" + imid;
    matSizingImageUrl += "&cropLeft=0";
    matSizingImageUrl += "&cropTop=0";
    matSizingImageUrl += "&cropRight=0";
    matSizingImageUrl += "&cropBottom=0";
    matSizingImageUrl += "&scale=1&dpi=" + matSizingDpi;
    matSizingImageUrl += "&sizeId=" + $("sizeId").value;
    matSizingImageUrl += "&middleMatId=" + $("middleMatId").value;
    matSizingImageUrl += "&bottomMatId=" + $("bottomMatId").value;
    $("imgMatted").src = matSizingImageUrl;
  	
  
    // Update the mat texture    
    var mat = $("divTopMat");
    mat.style.backgroundImage = "url(mats/tiles/" + $("topMatId").value + ".gif)";
    
    
    topInches=$("topMatSpacingTop").value;
    bottomInches=$("topMatSpacingBottom").value;
    leftInches=$("topMatSpacingLeft").value;
    rightInches=$("topMatSpacingRight").value;

    updateMatSizes(topInches, bottomInches, leftInches, rightInches);
}
function updateMatSizes(topInches, bottomInches, leftInches, rightInches) {
    var ppi = matSizingDpi;//
    var img = document.getElementById("imgMatted");
    var topMat = document.getElementById("divTopMat");
    // Limit and round the values
    topInches = Math.round(topInches*4) / 4;
    bottomInches = Math.round(bottomInches*4) / 4;
    leftInches = Math.round(leftInches*4) / 4;
    rightInches = Math.round(rightInches*4) / 4;
    var minInches = 2.5;
    var maxInches = 9.0;
    if (topInches < minInches) topInches = minInches;
    if (topInches > maxInches) topInches = maxInches;
    if (bottomInches < minInches) bottomInches = minInches;
    if (bottomInches > maxInches) bottomInches = maxInches;
    if (leftInches < minInches) leftInches = minInches;
    if (leftInches > maxInches) leftInches = maxInches;
    if (rightInches < minInches) rightInches = minInches;
    if (rightInches > maxInches) rightInches = maxInches;
            
    var topPixels = topInches * ppi;
    var bottomPixels = bottomInches * ppi;
    var leftPixels = leftInches * ppi;
    var rightPixels = rightInches * ppi;

    topMat.style.paddingLeft = leftPixels + "px";
    topMat.style.paddingRight = rightPixels + "px";
    topMat.style.paddingTop = topPixels + "px";
    topMat.style.paddingBottom = bottomPixels + "px";

		ServerRefresh();

}

function ApplyMatResize(topInches, bottomInches, leftInches, rightInches){
    $("topMatSpacingTop").value = topInches;
    $("topMatSpacingLeft").value = leftInches;
    $("topMatSpacingRight").value = rightInches;
    $("topMatSpacingBottom").value = bottomInches;
    
    $("mat_sizing_content").style.display = "none";
    //$("mat_sizing_new").style.display = "none";

    // Fix for IE bug, show all dropdowns
    var dd = document.getElementsByTagName("select");
    for (i=0; i < dd.length; i++) {
        dd[i].style.visibility = "visible";
    }            

    ServerRefresh();
}

function CancelMatResizeText() {
    $("mat_sizing_content").style.display = "none";
    //$("mat_sizing_new").style.visibility = "hidden";
    
    // Fix for IE bug, show all dropdowns
    var dd = document.getElementsByTagName("select");
    for (i=0; i < dd.length; i++) {
        dd[i].style.visibility = "visible";
    }            
}

// this shows the correct tab image and decides which mat color to highlight
function renderMats(button) {
	//render tabs
	var numMats = $('numMats');
	for(x = 1 ; x <= 3; x++)
	{
		var tab = $('matTab' + x);
		tab.className = button == x ? "matTab"+ x +"On" : "matTab"+ x; 
		x <= parseInt(numMats.value) ? tab.show():tab.hide();
	}
	
	  
	var moreMats = $('matMore');
	numMats.value == 3 ? moreMats.hide(): moreMats.show(); 
	
	
	//the X on the tab
	var X2Mat = $('no2Mat')
	numMats.value == 2 ? X2Mat.show(): X2Mat.hide(); 
	var X3Mat = $('no3Mat')
	numMats.value == 3 ? X3Mat.show(): X3Mat.hide();		
	
	switch (button) {
		case 1:
          ShowMat($('topMatId').value);
			break;
		case 2:
          ShowMat($('middleMatId').value);
	  
	      
			break;
		case 3:
      ShowMat($('bottomMatId').value);
			break;
		}
	if($('close2') != null)
		$('close2').style.display = (numMats.value == 2 ? "block" : "none");
	if($('close3') != null)
	$('close3').style.display = (numMats.value == 3 ? "block" : "none");


}

// 
function toggleNoMat() 
	{
	val = $('num_mats_0').checked;
	if (val) {
    $('numMats').value = 0;
	
	
  } else {
    $('numMats').value = ($('topMatId').value > -1 ? 1 : 0) + ($('middleMatId').value > -1 ? 1 : 0) + ($('bottomMatId').value > -1 ? 1 : 0);
    
    
  }
  switchMatTab($('numMats').value);
  enableMatPanel();

  ServerRefresh();
}
// needs to be seperated out so we can force a refresh on switching to the mat tab, without calling a ServerRefresh
//  these vars initialized in initFrameshop
var matPanelOverlay;
var matPanelContainer;
var matPanelDropdown;

//creating an object that we will use for each mat thumb
var matThumbs = function(id, colorId, collectionId, name)
{
 var outterDiv = document.createElement('div');
 outterDiv = $(outterDiv)
 outterDiv.id = 'mat_'+id;
 outterDiv.title =  name; 
 outterDiv.className = 'matThumb color_' +colorId + ' collection_' +collectionId
var info = document.createElement('div');
info = $(info);
info.id = 'info_'+id;
info.className = 'matInfo';
	info.observe('click', function(event)
	{
		infoClicked = true;
		MatPopup(id);
	})
	var imageURL = "url(http://d3br5i6ykfuol.cloudfront.net/mats/75x75/"+id+"F_M_MPT.jpg)"
	outterDiv.setStyle({backgroundImage:imageURL});

	outterDiv.observe('click', 
		function(event)
		{
			if(infoClicked)
			{
				infoClicked = false;
				return;
			}
		SetMat(id,name);
		})
	outterDiv.observe('mouseover', 
	function(event)
	{ 
		var el = Event.element(event)
		if(el.hasClassName('matThumb'))
		{
			el.addClassName('matThumbOver');
			el.removeClassName('ThumbOver');
			el.down().addClassName('matInfoOver');
			el.down().removeClassName('matInfo');
			
			var name = el.id.substring(el.id.indexOf("_"), 100)
			
		
		}
	})

	outterDiv.observe('mouseout',  
	function(event)
	{ 
		var el = Event.element(event)
		if(el.hasClassName('matThumbOver'))
		{
			el.addClassName('matThumb');
			el.removeClassName('matThumbOver');
			el.down().removeClassName('matInfoOver');
			el.down().addClassName('matInfo');
		}
	})

	outterDiv.appendChild(info)

return outterDiv;
}

function enableMatPanel() 
{
	//if the panel is empty fill it

	matPanelOverlay = $("grayout3_overlay");
		matPanelContainer = $("grayout3");
		matPanelDropdown = $('mat_category_dropdown_color');
		val = $('num_mats_0').checked;
		if (val) 
		{
			matPanelOverlay.style.display = "block";
			matPanelOverlay.style.width = matPanelContainer.offsetWidth + "px";
			matPanelOverlay.style.height = matPanelContainer.offsetHeight + "px";
			matPanelDropdown.style.visibility = 'hidden';
		}
		else
		{
			matPanelOverlay.style.display = "none";
			matPanelDropdown.style.visibility = 'visible';
		}


	if(!/[a-z]/.test($('mat_category_dropdown_color').innerHTML))
	{
		switchMatTab(1)
	
	
		new Ajax.Request('../../../usercontrols/frameshop/mat/MatAjax.ashx',
        { method:'get'
        ,   parameters: {num: escape(Date()), topMatId:$('topMatId').value} 
        ,   'onError':      function(req) { alert(req.responseText); }
        ,   'onSuccess': 
			function(req) 
			{
				var response = (req.responseText).evalJSON();
        		colors = response.MatColors;
				collections = response.MatCollections;
				mats = response.Mats;
				defaultMat = response.defaultMat;
	
				var select = $('mat_category_dropdown_color');
				for (var i = 0 ; i < colors.length ; i++) 
				{   			
				    if (colors[i] != null) 
				    {
					    select.insert(new Element('option', {value:'color_'+ colors[i].id}).update(colors[i].name))		
					}
				}  
			
				select.insert(new Element('option', {value: '', innerHTML: '------------------'}))	
			
		        for (var j = 0 ; j < collections.length ; j++) 
			    { 
					if (collections[j] != null) 
					{
					    select.insert(new Element('option', {value: 'collection_'+collections[j].id}).update(collections[j].name))		
					}
				} 
			
				var matScroller = $('mat_scroller');
			
				for (var k = 0 ; k < mats.length - 1 ; k++) 
				{   			
					matScroller.insert(matThumbs(mats[k].id,mats[k].colorId,mats[k].collectionId, mats[k].name))		
				} 
				var totalMats = parseInt($('numMats').value);
				switchMatTab(totalMats);
			 }
        }
    );
  }
}


function addMatTab() 
{
	var totalMats = parseInt($('numMats').value);
	
	//if there are no mats available
	if(totalMats == 0)
	{
		$('num_mats_0').checked = false;
		toggleNoMat();
	}
	totalMats += 1;
 	switchMatTab(totalMats);
}

// called to switch between mat tabs 
function switchMatTab(button) {

var returnMat;
if(typeof(closeTag) != 'undefined' && closeTag == 1)
{	closeTag = 0
	button--;
}


	var numMats = $('numMats');
	if (button > numMats.value) {
		// added a mat

		numMats.value = button;
		if (button == 1) {
			// added first mat
			//don't add a default mat if artist configured it with no mat
			if ($('topMatId').value == -1 && byArtist != 'True') {
				$('topMatId').value = DEFAULTMAT; 
			}
		}
		if (button == 2) {
			// added second mat
			if ($('middleMatId').value == -1) {
				$('middleMatId').value = DEFAULTMAT; 
			}
		}
		else if (button == 3) {
			// added third mat
			$('bottomMatId').value = $('bottomMatId').value;
			$('bottomMatId').value = DEFAULTMAT; 			
		}

		ServerRefresh();
	}

	switch(button)
	{


		case 1:
			returnMat = $('topMatId').value 
    	break;
		case 2:
			returnMat = $('middleMatId').value 
		break;
		case 3:
			returnMat = $('bottomMatId').value 
		break;


	}


	currentMatTab = button;
	renderMats(currentMatTab);
	highlightMat(returnMat);
	
}

// removes a tab
function closeTab(num) {
	$('numMats').value = Number($('numMats').value) - 1;
	closeTag = 1;
	renderMats(num - 1);
	ServerRefresh();
}

// shows the correct mats for a given mat drop-down selection
function FilterMats() {

    var id=$('mat_category_dropdown_color').value;

    //someone selects the seperator
    if(id=='')
    return;

    $$('.matThumb').each(function(el){el.hide(); })

    $$('.matThumbOn').each(function(el){el.hide(); })
    $$('.'+id).each(function(el){el.show();})
}

// finds the right drop-down selection for a given mat, then selects it, filters the mats, and highlights the mat
function ShowMat(id) {


    if(id == '-1')
    {
        id = DEFAULTMAT
    }

	if($("mat_"+id) == null)
	return;
	
	var divID = $("mat_"+id).className;

    var tempString = divID.substring(divID.indexOf("color_"));
	var colorID = tempString.substring(0, divID.indexOf(" ")).replace(/\s/,'');
	
	var options = $('mat_category_dropdown_color').options;
    for (var i = 0; i < options.length; i++) 
    {
        if (options[i].value == colorID)
        {
            options[i].selected = true;
		}
	}
	
   FilterMats();

}

// selects the given mat for the current mat layer
function SetMat(id, name) {

    $("currentSelectionDisplay").update(name);
    switch (currentMatTab) {
    	case 1:
    		$('topMatId').value = id;
    		topMatName = name;
    		break;
    	case 2:
    		$('middleMatId').value = id;
	   		middleMatName = name;
	   		break;
    	case 3:
    		$('bottomMatId').value = id;
	    		bottomMatName = name;
    		break;
    	}
    //highlite thumb
    highlightMat(id);

    ServerRefresh();    
    
            
}

// highlights the given mat as chosen
function highlightMat(id)
{
    if(id == -1)
    id = DEFAULTMAT

    var el = $('mat_' + id);

    if(el == null) return;
	if(el.hasClassName('matThumb'))
	{
		var oldMat = $$('.matThumbOn')
		if(oldMat[0] != null)
		{
		oldMat[0].addClassName('matThumb');
		oldMat[0].removeClassName('matThumbOn');
		if(oldMat[0].hasClassName('matThumbOver'))
			oldMat[0].removeClassName('matThumbOver');
		oldMat[0].down().removeClassName('matInfoOver');
		oldMat[0].down().addClassName('matInfo');
		}
	
		el.addClassName('matThumbOn');
		el.removeClassName('matThumb');
		el.removeClassName('matThumbOver');
		el.down().removeClassName('matInfo');
		el.down().addClassName('matInfoOver');
	}
  	mat_thumb_selected = id;
  	
  	// Display paper info below 
    $$(".divMatInfo").each(function(el){el.hide();})
    $("divMatInfo_" + id).style.display = "block";   
}

// mat rollover on
function mat_thumb_over(id_ro){
  if(mat_thumb_selected != id_ro){
    $("mat_thumb_ro_"+id_ro).style.border="solid 3px #0099cc";
  }
}

// mat rollover off
function mat_thumb_out(id_out){
  if(mat_thumb_selected != id_out){
    $("mat_thumb_ro_"+id_out).style.border="solid 0px #000000";
  }
}

// *** PAPER ***
function SetPaperType(materialID) {
    $("materialId").value = materialID;
    ServerRefresh();
    
    //unhighlight old thumb 
    if(paper_thumb_selected!=0){
      $("rbPaper_"+paper_thumb_selected).style.border="solid 0px #000000";
    }
    
    paper_thumb_selected=materialID;
    
    //highlite thumb
    $("rbPaper_"+materialID).style.border="solid 3px #70c132";
    
    // Display paper info below 
    $$(".divPaperInfo").each(function(el){el.hide();})
    $("divPaperInfo_" + materialID).style.display = "block";
}
function paper_thumb_over(id_ro){
  if(paper_thumb_selected != id_ro){
    $("rbPaper_"+id_ro).style.border="solid 3px #0099cc";
  }
}
function paper_thumb_out(id_out){
  if(paper_thumb_selected != id_out)
  {
    $("rbPaper_"+id_out).style.border="solid 0px #000000";
  }
}

// *** FRAME ***

// frame NOT enabled only if we have museum wrap selected AND no frame ID.
function IsFrameEnabled() {
	return !(($('materialId').value == 5 || $('materialId').value == 8 || $('materialId') == 10).value && $('frameID').value <= 0);
}
// probably just used on frame nav path init?  NOT for Canvas
function ShowFrame(id) {

    var framePanelID = $("frame_thumb_ro_"+id).parentNode.className;
    framePanelID = framePanelID.substring(0, framePanelID.indexOf("_")).replace("color", "");
    
    var frameBox = $('ddlFrameCategories').options; 
    //Set Customer Favorites to default
    for (var i = 0; i < frameBox.length; i++) {
        if (frameBox[i].value == "'collection', 1")
            frameBox[i].selected = true;
    }
    FilterFrameList();
}

// just deselect the old frame and highlight the new one, w/ server refresh
function SetFrame(id, name) {
    //unhighlight old frame 
    if (id<=0)  {id = DEFAULTFRAME ; toggleNoMat();}
     
    if(frame_thumb_selected!=0 )  
		$("frame_thumb_ro_" + frame_thumb_selected).style.border="solid 0px #000000";
    
    frame_thumb_selected=id;
    
    //highlite selected frame thumb
    if($("frame_thumb_ro_"+id) != null)
    $("frame_thumb_ro_"+id).style.border="solid 3px #70c132";
    
    // Store new frame in hidden field
    $("frameID").value = id;
    ServerRefresh();
		
    $("spanAttribute").innerHTML = name;  
    
    // Display paper info below 
    $$(".divFrameInfo").each(function(el){el.hide();})
    $("divFrameInfo_" + id).style.display = "block";
}

function FilterFrameList() {
      
      var frameBoxCategory = $("ddlFrameCategories");
      var frameBoxColor = $("ddlFrameColor");
      
	  filterValueCategory = frameBoxCategory.options[frameBoxCategory.selectedIndex].value;
	  filterValueCategory = filterValueCategory.split(",");
	  filterValueColor = frameBoxColor.options[frameBoxColor.selectedIndex].value;
	  filterValueColor = filterValueColor.split(",");
	  
	  filterValueCategory[0]=String(filterValueCategory[0]);
	  filterValueCategory[1]=eval(filterValueCategory[1]);
	  filterValueColor[0]=String(filterValueColor[0]);
	  filterValueColor[1]=eval(filterValueColor[1]);
      
      var scroller = $("molding_scroller");
      var frames = scroller.getElementsByTagName("div");
   
      var count = 0;
      if (frames && scroller) {           
           // Filter based on both category and color selection  (if one or the other is set to "show all", ignore that one)                    
           for (i=0; i < frames.length; i++) {
             if ((frames[i].className.indexOf(filterValueCategory[0] + filterValueCategory[1] + "_") >= 0 || frameBoxCategory.selectedIndex == 0) && (frames[i].className.indexOf(filterValueColor[0] + filterValueColor[1] + "_") >= 0 || frameBoxColor.selectedIndex == 0))  {                     
                frames[i].style.display = "block";
                
                // Populate images
                var images = frames[i].getElementsByTagName("img");
                for (j=0; j < images.length; j++) {
                    if (images[j].className != "spacer" && images[j].src.indexOf("thumb_plus.gif") < 0 && images[j].src.indexOf("icon_eco_sm.png") < 0) {
                        var moulding_id = images[j].id.substring(11, images[j].id.length);
                        images[j].src = "http://d3br5i6ykfuol.cloudfront.net/frames/corner75/" + moulding_id + "C_FR_MPT.jpg";
                    }
                }
                count++;
             } else {
                frames[i].style.display = "none";                 
             }          
         }
    }
    
    if (count == 0)
    {
        $('divNoFramesInCategory').style.display = "block";
    }
    else
    {
        $('divNoFramesInCategory').style.display = "none";
    }
    
    // Highlight the current attribute    
    /*var selectedCategory = "molding_attribute_" + frameBoxCategory.selectedIndex;
    var selectedColor = "molding_attribute_" + frameBoxColor.selectedIndex;
    var attribLinks ; 
    if ($("frame_attributes"))
        attribLinks = $("frame_attributes").getElementsByTagName("option");
    
    if (attribLinks){
    for (i=0; i < attribLinks.length; i++) {
            if (attribLinks[i].id == selectedCategory || attribLinks[i].id == selectedColor) {
                attribLinks[i].className = "selected";    
                
            } else {
                attribLinks[i].className = "";
            }
        }    
    }*/
}

function SortFrames(sortValue)
{

}

// * * * CANVAS FRAMING * * *
// this stuff will ONLY happen in the CANVAS nav path - no enabling / disabling in FRAME nav path
function SetFrameEnabled() {
	enabled = $('cbFrameEnabledTrue').checked;
    if (!enabled) {
        // Turn off the frame, mats and glazing
        $("frameID").value = 0;
        
        // Un-highlight all frames
        var scroller = $("molding_scroller");
        var frames = scroller.getElementsByTagName("table");
        if (frames && scroller) {
            for (i=0; i < frames.length; i++) {
                frames[i].getElementsByTagName("tr")[0].className = "";
            }
        }
    } else {
        if (!($("frame_thumb_ro_"+$("frameID").value)	&& $("frame_thumb_ro_"+$("frameID").value).parentNode.style.display == 'block')) {
					if ($("frame_thumb_ro_"+frame_thumb_selected)	&& $("frame_thumb_ro_"+frame_thumb_selected).parentNode.style.display == 'block') {
		        $("frameID").value = frame_thumb_selected;
		      } else {
		        $("frameID").value = DEFAULTFRAME;
		      }
		    }
				// select  current frame	  
				SetFrame($("frameID").value);
				eval(unescape($('frame_thumb_ro_'+$('frameID').value).href).replace("javascript:", ""));
	      
    }
    enableFramePanel(enabled);
    ServerRefresh();
}
// goes with previous function.  we separate this out so we can call it on switching to frame tab (and not need to call ServerRefresh()) 
//  it won't work when frame tab isn't visible;
function enableFramePanel(enabled) {
	if (enabled == undefined) 
		enabled = $('cbFrameEnabledTrue').checked;
	if (!enabled) {
        //  Gray out frame options
        var container = $("divFrameSelection");
        var overlay = $("divFrameSelectionOverlay");
        overlay.style.display = "block";
        overlay.style.width = container.offsetWidth + "px";
        overlay.style.height = container.offsetHeight + "px";
	} else {
        //  Un-gray out frame options
        var overlay = $("divFrameSelectionOverlay");
        overlay.style.display = "none";
  }
}
function FilterFramesByCanvas() {
    var scroller = $("molding_scroller");
    var frames = scroller.getElementsByTagName("div");
    if (frames && scroller) {
        for (i=0; i < frames.length; i++) {
            if (frames[i].className.indexOf("canvasTrue") >= 0) {
                frames[i].style.display = "block";
                
                // Populate images
                var images = frames[i].getElementsByTagName("img");
//                var spans = frames[i].getElementsByTagName("span");
                for (j=0; j < images.length; j++) {
                    if (images[j].className != "spacer" && images[j].src.indexOf("thumb_plus.gif") < 0) {
                        var moulding_id = images[j].id.substring(11, images[j].id.length);
                        images[j].src = "http://d3br5i6ykfuol.cloudfront.net/frames/corner75/" + moulding_id + "C_FR_MPT.jpg";
//                          priceval=spans[j].innerHTML;
//                          if(priceval<=10){
//                            spans[j].innerHTML="$";
//                          }else if((priceval>10)&&(priceval<=15)){
//                            spans[j].innerHTML="$$";
//                          }else if(priceval>15){
//                            spans[j].innerHTML="$$$";
//                          }else{
//                            spans[j].innerHTML="$";
//                          } 
                    }
                }                
            } else {
                frames[i].style.display = "none";
            }
        }
    }
}
function frame_thumb_over(id_ro){
  if(frame_thumb_selected != id_ro){
    $("frame_thumb_ro_"+id_ro).style.border="solid 3px #0099cc";
  }
}
function frame_thumb_out(id_out){
  if(frame_thumb_selected != id_out){
    $("frame_thumb_ro_"+id_out).style.border="solid 0px #000000";
  }
}


// update size
function selectSize(sizeID, y, x) {
    $("sizeId").value = sizeID;
    if(y != undefined)
    {
        $("imageHeight").value = y;
        $("imageWidth").value = x;
	}

	// force No Wrap for massive size and very small sizes
	if (selectedNavPath == 'canvas') {
	  if ($('sizeId').value == 6) {
	  	$('rdoGallery2').disabled = true;
	  	$('rdoGallery1').disabled = true;
	  	$('pBarWrapsDisabled').style.display = 'block';
 	    $('pBarWrapsDisabled2').style.display = 'none';
	  } else if ($("imageHeight").value < 8 || $("imageWidth").value < 8) { //smaller than 8" on the shortest side, can't do gallery wrap
	    if ($("imageHeight").value < 6 || $("imageWidth").value < 6) { //smaller than 6" on the shortest side, can't do museum or gallery wrap
	  	    $('rdoGallery1').disabled = true;
	  	} else {
	  	    $('rdoGallery1').disabled = false;
	  	}
  	    $('rdoGallery2').disabled = true;  	    
	  	$('pBarWrapsDisabled').style.display = 'none';
 	    $('pBarWrapsDisabled2').style.display = 'block'; //display too small message
	  } else {
	  	$('rdoGallery2').disabled = false;
	  	$('rdoGallery1').checked = true;
	  	$('rdoGallery1').disabled = false;
	  	$('pBarWrapsDisabled').style.display = 'none';
 	    $('pBarWrapsDisabled2').style.display = 'none';
	  }
	}
    ServerRefresh();
}
// update glazing
function SetGlazing(glazingID) {
    $("glazingId").value = glazingID;
    ServerRefresh();
}

// support function
function GetPricingQueryString() {
    
    
    var url = "IMID="+imid;
    url += "&sizeId=" + $("sizeId").value;
    url += "&cropLeft=" + document.getElementById("cropLeft").value;
    url += "&cropTop=" + document.getElementById("cropTop").value;
    url += "&cropRight=" + document.getElementById("cropRight").value;
    url += "&cropBottom=" + document.getElementById("cropBottom").value;
    if (IsFrameEnabled()) {
         url += "&frameId=" + $("frameID").value;
        var numMats = $("numMats").value;
        
        var topMatID = "-1";
        var middleMatID = "-1";
        var bottomMatID = "-1";
        var topMatSpacingTop = "0";
        var topMatSpacingLeft = "0";
        var topMatSpacingRight = "0";
        var topMatSpacingBottom = "0";
        var middleMatSpacingTop = "0";
        var middleMatSpacingLeft = "0";
        var middleMatSpacingRight = "0";
        var middleMatSpacingBottom = "0";
        var bottomMatSpacingTop = "0";
        var bottomMatSpacingLeft = "0";
        var bottomMatSpacingRight = "0";
        var bottomMatSpacingBottom = "0";        
        
        if (null != $("topMatId")) {
            topMatID = $("topMatId").value;
        }
        if (null != $("middleMatId")) {
            middleMatID = $("middleMatId").value;
        }
        if (null != $("bottomMatId")) {
            bottomMatID = $("bottomMatId").value;
        }
        
        if (null != $("topMatSpacingTop")) {
            topMatSpacingTop = $("topMatSpacingTop").value;
        }
        if (null != $("topMatSpacingLeft")) {
            topMatSpacingLeft = $("topMatSpacingLeft").value;
        }
        if (null != $("topMatSpacingBottom")) {
            topMatSpacingBottom = $("topMatSpacingBottom").value;
        }
        if (null != $("topMatSpacingRight")) {
            topMatSpacingRight = $("topMatSpacingRight").value;
        }
        
        if (null != $("middleMatSpacingTop")) {
            middleMatSpacingTop = $("middleMatSpacingTop").value;
        }
        if (null != $("middleMatSpacingLeft")) {
            middleMatSpacingLeft = $("middleMatSpacingLeft").value;
        }
        if (null != $("middleMatSpacingBottom")) {
            middleMatSpacingBottom = $("middleMatSpacingBottom").value;
        }
        if (null != $("middleMatSpacingRight")) {
            middleMatSpacingRight = $("middleMatSpacingRight").value;
        }
        
        if (null != $("bottomMatSpacingTop")) {
            bottomMatSpacingTop = $("bottomMatSpacingTop").value;
        }
        if (null != $("bottomMatSpacingLeft")) {
            bottomMatSpacingLeft = $("bottomMatSpacingLeft").value;
        }
        if (null != $("bottomMatSpacingBottom")) {
            bottomMatSpacingBottom = $("bottomMatSpacingBottom").value;
        }
        if (null != $("bottomMatSpacingRight")) {
            bottomMatSpacingRight = $("bottomMatSpacingRight").value;
        }
        
        if (numMats > 0) {
            url += "&topMatId=" + topMatID;
            if (numMats > 1) {
                url += "&middleMatId=" + middleMatID;
                if (numMats > 2) {
                    url += "&bottomMatId=" + bottomMatID; 
                }
            }
        }
        
        url += "&topMatSpacingTop=" + topMatSpacingTop;
        url += "&topMatSpacingLeft=" + topMatSpacingLeft;
        url += "&topMatSpacingRight=" + topMatSpacingRight;
        url += "&topMatSpacingBottom=" + topMatSpacingBottom;
        
        url += "&middleMatSpacingTop=" + middleMatSpacingTop;
        url += "&middleMatSpacingLeft=" + middleMatSpacingLeft;
        url += "&middleMatSpacingRight=" + middleMatSpacingRight;
        url += "&middleMatSpacingBottom=" + middleMatSpacingBottom;
        
        url += "&bottomMatSpacingTop=" + bottomMatSpacingTop;
        url += "&bottomMatSpacingLeft=" + bottomMatSpacingLeft;
        url += "&bottomMatSpacingRight=" + bottomMatSpacingRight;
        url += "&bottomMatSpacingBottom=" + bottomMatSpacingBottom;        
        
        url += "&glazingId=" + $("glazingId").value;
    }
    url += "&materialId=" + document.getElementById("materialId").value;
    return url;
}

// *** SERVER REFRESH ***
var doRefresh = false;
function ServerRefresh(kickoff) {
 
		// don't refresh until kickoff=true
		if (kickoff) doRefresh = true;
		if (!doRefresh)
			return;
			
       $('lblTotal').innerHTML = '<img src="/images/icons/smallAJAX.gif"> Calculating';

		// avoid waiting for image refresh
		document.body.style.cursor = 'wait';
        
        setTimeout("UpdateImageUrl()", 0);
		//UpdateImageUrl(); 
		
		if (selectedNavPath == 'frame') {
			UpdateGlazingOptions();
		
		} 
		else {

		  InitiatePricingUpdate();
		  RequestServerSideValidation();
		   
		}
}

// *** UPDATE IMAGE ***
function UpdateImageUrl() 
{
	var bigImage = $("imgFramed");
	var thumb = $('imgSmall');
	bigImage.src = "/services/frame_engine.ashx?" + GetPricingQueryString();   
	thumb.src = bigImage.src;
	if($("imageWidth").value != undefined)
	{
	var framePadding  = 0;
	var verticleMatPadding  = 0;
		var horizontalMatPadding  = 0;
	if(($('frameID').value ) != 0)
	{
		framePadding = 3 * 1.5625 ;
		verticleMatPadding = ($('topMatSpacingTop').value * 1.5625) + ($('topMatSpacingBottom').value * 1.5625);	
		horizontalMatPadding = ($('topMatSpacingRight').value * 1.5625) + ($('topMatSpacingLeft').value * 1.5625) ;
	}
   	thumb.width =  ($("imageWidth").value * 1.5625) + horizontalMatPadding + framePadding
	thumb.height =  ($("imageHeight").value  * 1.5625) + verticleMatPadding + framePadding
	}
	else
	{
	if($('sizeId').value==2){
	    scaleMore=1;
	}else if($('sizeId').value==1){
	    scaleMore=12;
	}else{
    	scaleMore=0;
	}
    $('imgSmall').width=(((7-$('sizeId').value)+12)*$('sizeId').value)+scaleMore;

	}
}

// *** UPDATE GLAZING OPTIONS ***
function UpdateGlazingOptions() {
									
	AjaxRequest.post(
	    {
	        'url':          'services/get_dimensions.ashx',
	        'content':      GetPricingQueryString(),
	        'onSuccess':    function(req) {
	                            var values = req.responseText.split(",");
	                            printWidth = values[0];
	                            printHeight = values[1];
	                            frameWidth = values[2];
	                            
	                            var ui = parseInt(printWidth) + parseInt(printHeight);
	                            if (IsFrameEnabled()) {
	                                var numMats = parseInt($("numMats").value);
	                                if ($("topMatId").value > 0 && numMats > 0) {
	                                    ui += parseInt($("topMatSpacingTop").value);
	                                    ui += parseInt($("topMatSpacingBottom").value);
	                                    ui += parseInt($("topMatSpacingLeft").value);
	                                    ui += parseInt($("topMatSpacingTop").value);
	                                }
	                                if ($("middleMatId").value > 0 && numMats > 1) {
	                                    ui += 1;
	                                }
	                                if ($("bottomMatId").value > 0 && numMats > 2) {
	                                    ui += 1;
	                                }
	                            }	                            
				                /*$('glazing_1').disabled = ui >= 44;
                				$('glazing_2').disabled = ui >= 44;
					            $('glazing_3').disabled = ui >= 44;	*/
				                $('glazing_span_1').className = (ui < 44) ? "" : "disabled";
				                $('glazing_span_2').className = (ui < 44) ? "" : "disabled";
				                $('glazing_span_3').className = (ui < 44) ? "" : "disabled";				                
				                if (ui >= 44) 
				                {
				                    $('glazing_span_1').style.display = "none";
				                    $('glazing_span_2').style.display = "none";
				                    $('glazing_span_3').style.display = "none";
				                }	
	                            $('pGlassDisabled').style.display = (ui<44) ? "none" : "block";
								if (ui >= 44 && $('glazingId').value <= 3) 
								{
								    $('glazingId').value = DEFAULTGLAZING;
									$('glazing_4').checked = true;
								}

								InitiatePricingUpdate();
								
								RequestServerSideValidation();

	                        },
	        'onError':      function(req) { alert("Ajax error!"); }
	    }
	);
}

// *** INITIATE PRICING UPDATE ***
function InitiatePricingUpdate() {    
    var query = ""; 
    var mode = $("getmode").value ; 
    if (mode.toLowerCase() == "gallerysetup") query = "&mode=gallerysetup" ; 
    
    if (query == "")
        query = GetPricingQueryString() ; 
    else 
        query = GetPricingQueryString() + query ; 
       
    AjaxRequest.post(
        {
            'url':          'services/PricingDetails.aspx?br=' + $("brand").value ,
            'content':      query,
            'onSuccess':    function(req) {
                                $("pricing_table_wrapper").innerHTML = req.responseText;
                            },
            'onError':      function(req) { alert("Ajax error!"); }
        }
    );
    
    AjaxRequest.post(
        {
            'url':          'services/PricingDetails.aspx?br=' + $("brand").value ,
            'content':      query + "&command=total",
            'onSuccess':    function(req) {
                                $("lblTotal").innerHTML = req.responseText;
                            },
            'onError':      function(req) { alert("Ajax error!"); }
        }
    );
}
/// *** REQUEST SERVER SIDE VALIDATION ***
function RequestServerSideValidation() {
 
   AjaxRequest.post(
        {
            'url':          'services/validate_frameshop_finish.ashx',
            'content':      GetPricingQueryString(),
            'onSuccess':    function(req) {
                                var val = $("divValidation");
                                if (req.responseText == "OK") {
                                    val.style.display = "none";
                                    configurationIsValid = true;
                                } else {
                                    val.style.display = "block";
                                    val.innerHTML = req.responseText;
                                    configurationIsValid = false;
                                }
															document.body.style.cursor = 'default';
                            
                            },
            'onError':      function(req) {
            							 		document.body.style.cursor = 'default';
															alert("Ajax error!"); 
														}
        }
    );
}

// *** POPUPS ***
function PaperPopup(materialID) {
    var popup = window.open("/create/popup.aspx?MID=" + materialID, "MediaDetail", "scrollbars,resizable,width=540,height=750");
    popup.focus();
}
function MatPopup(matID) {
    var popup = window.open('MatDetail.aspx?MID=' + matID, 'MatDetail', 'width=330,height=600');
    popup.focus();
}
function FramePopup(frameID) {
    var popup = window.open('FrameDetail.aspx?FID=' + frameID, 'FrameDetail', 'scrollbars,resizable,width=515,height=750');
    popup.focus();
}
function FramePopupGreen(frameID, isGreen) {
    var popup = window.open('FrameDetail.aspx?FID=' + frameID + "&isgreen=" + isGreen, 'FrameDetail', 'scrollbars,resizable,width=515,height=750');
    popup.focus();
}
function FramePopupCurrent() {
    var current = $("frameID").value;
    FramePopup(current);
}

// *********************************
// *** HELPER FUNCTIONS AND INIT ***
// *********************************
// calculate material id
function calculateMaterialId() {
  if (selectedNavPath != 'canvas')	 // only calculate material id from wrap and finish if we're in Canvas 
  	return;

	var wrapOffset;  // offset in Material table
	var finishId; // starting point of finishes in Material table
	/*if ($('rdoGallery1').checked)
		wrapOffset = 0;
	if ($('rdoGallery2').checked)
		wrapOffset = 1;
		
	if ($('rdoPremier').checked)
		finishId = 5;
	if ($('rdoPiezo').checked)
		finishId = 10;
	
	if (museum) 
		$("materialId").value = 8 + wrapOffset;
	else
		$("materialId").value = finishId + wrapOffset;*/
		
	// Damian Murphy 2010.11.11
	// No more finishID - we've removed the canvas type and frame
	// options from the canvas process.
    if ($('rdoGallery1').checked)
    {
        $('divCanvasGalleryWrapColor').show();
        $('divCanvasFloatingFrameColor').hide();
    
		if ($('rdoWrapColorWhite').checked)
		{
		    $("materialId").value = 17;
		} 
		else if ($('rdoWrapColorBlack').checked)
		{
		    $("materialId").value = 18;
		} 
		else if ($('rdoWrapColorImageWrap').checked)
        {
		    $("materialId").value = 26;
		}     
    }
	if ($('rdoGallery2').checked)
	{
	    $('divCanvasGalleryWrapColor').show();
        $('divCanvasFloatingFrameColor').hide();
	
		if ($('rdoWrapColorWhite').checked)
		{
		    $("materialId").value = 19;
		} 
		else if ($('rdoWrapColorBlack').checked)
		{
		    $("materialId").value = 20;
		} 
		else if ($('rdoWrapColorImageWrap').checked)
        {
		    $("materialId").value = 27;
		}     
    }
    if ($('rdoGallery3').checked)
	{
		$('divCanvasGalleryWrapColor').hide();
        $('divCanvasFloatingFrameColor').hide();
        
        $("materialId").value = 21;
    }
    if ($('rdoGallery4').checked)
	{
		$('divCanvasGalleryWrapColor').hide();
        $('divCanvasFloatingFrameColor').show();
        
        if ($('rdoFloatingFrameWrapColorBlack').checked)
		{
		    $("materialId").value = 22;
		} 
		else if ($('rdoFloatingFrameWrapColorGold').checked)
		{
		    $("materialId").value = 23;
		} 
		else if ($('rdoFloatingFrameWrapColorWhite').checked)
		{
		    $("materialId").value = 24;
		} 
		else if ($('rdoFloatingFrameWrapColorBrown').checked)
		{
		    $("materialId").value = 25;
		} 
    }
   
    // hide frame tab for gallery and nowrap
    if (wrapOffset == 2){
        $("frameID").value = 0;
        //$("imgCanvasFrame").hide();
        $("imgCanvasCart2").hide();
        $("imgCanvasCart").show();
    } else {
//    	if ($('cbFrameEnabledTrue').checked) {
//	      $("frameID").value = DEFAULTFRAME;
//	    } else {
//	    	$("frameID").value = 0;
//			}
        SetFrameEnabled();
        //$("imgCanvasFrame").show();
        $("imgCanvasCart2").show();
        $("imgCanvasCart").hide();
    }
    updatePrevNextButtons();
}

// used when loading or switching nav paths
function initPaper() {
	if ($("rbPaper_"+$('materialId').value))
  	SetPaperType($('materialId').value);
  else if ($("rbPaper_"+paper_thumb_selected))
  	SetPaperType(paper_thumb_selected);
  else
  	SetPaperType(DEFAULTPAPER);
}

// var gets set from .cs file.  
var initialNavPath;
function initFrameShop() {
	museum = ($('isMuseum').value == 'true');
	
	navListSelect(initialNavPath);
}

function navListSelect(selected) {
	selectedNavPath = selected.replace("nav_", "");
	
	// turn off server refreshes while we switch areas
	doRefresh = false;

	// show recommendation panel only if in custom frame for museum art
	$('divCanvasTransferMuseumDescription').hide();
	//$('divCanvasTransferMemberDescription').hide();
	
	// load new content
    switch(selectedNavPath) {
    
        case 'frame':
            enableMatPanel.delay(5);
            if (museum)
            {
                $('divMFrameSteps').show();
                $('divFrameSteps').hide();
            }
            else
            {
                $('divFrameSteps').show();
                $('divMFrameSteps').hide();
            }
                
            $('divCanvasSteps').hide();
            $('divPrintSteps').hide();
            
    		$('divCanvasFrameText').hide();
    		$('divFrameAttributes').show();

            // init frame
            $('divFrameEnabled').hide();
			if ($('frameID').value <= 0)
			if ($('frame_thumb_ro_'+frame_thumb_selected))
                $('frameID').value = frame_thumb_selected;
            else
                $('frameID').value = $('artistFrameID').value;
		            
          	SetFrame($('frameID').value);
          	ShowFrame($('frameID').value);
            eval(unescape($('frame_thumb_ro_'+$('frameID').value).href).replace("javascript:", "").replace("%20", " "));
							
            // init mats
            $('numMats').value = ($('topMatId').value > -1 ? 1 : 0) + ($('middleMatId').value > -1 ? 1 : 0) + ($('bottomMatId').value > -1 ? 1 : 0);
          	$('num_mats_0').checked = ($('numMats').value == 0);
          	
			if ($('glazingId').value <= 0) {
				$('glazingId').value = DEFAULTGLAZING;
				$('glazing_4').checked = true;
			}

            if (museum) 
            {
                selectStep($('imgMFrameFrame'));
            } 
            else 
            {
                selectStep($('imgFrameSize'));
            }
            
            // run this even if we're in museum; resets paper to defaulr
            initPaper();
          	
            break;
        case 'canvas':
            if (museum)
            {
                $('divMCanvasSteps').show();
                $('divCanvasSteps').hide();
            }
            else
            {
                $('divCanvasSteps').show();
                $('divMCanvasSteps').hide();
            }
            $('divFrameSteps').hide();
            
    		$('divCanvasFrameText').show();
    		$('divFrameAttributes').hide();

			// init frame
            $('divFrameEnabled').show();
            FilterFramesByCanvas();
						
            $('numMats').value =0;

            $('glazingId').value = -1;

            if (museum) 
            {
        		$('divCanvasTransferMuseumDescription').show();
                selectStep($('imgMCanvasWrap'));
            } else {
        		//$('divCanvasTransferMemberDescription').show();
                // forces update of mat panel based on size...
                selectSize($("sizeId").value);	
                selectStep($('imgCanvasSize'));
            }
			calculateMaterialId();
            break;
        case 'print':
    		if (museum) {
    			window.location="/AddtoCart.aspx?IMID=" + imid + "&PrintOnly=1";
    			return;
    		} 
    		$('divCanvasFrameText').hide();
    		$('divFrameAttributes').show();

            // init paper - try to get previous selection, then 
            initPaper();
            $('frameID').value = 0;
            $('glazingId').value = -1;
            
            selectStep($('imgPrintSize'));
            
            $('numMats').value =0;
            break;
    }
    ServerRefresh(true);
}
// panel tabs
var selectedStep;
var selectedView;
function selectStep(selected) 
{
	document.getElementById("divColors").style.display="none";

    // start switching panels
    
    var currentStep = selected.id.replace("imgCanvas", "").replace("imgFrame", "").replace("imgPrint", "").replace("imgMFrame", "").replace("imgMCanvas", "");
    var currentView = selected.id.replace(currentStep, "") //frame, canvas or print view
	var tab = $(currentView + selectedStep);
	var div = $('div' + selectedStep);
	var divDescription = $('div' + selectedStep + 'Description');
	var divSelectedInfo = $('SelectedInfo_' + selectedStep);

	// hide previously selected div		
	if (div) 
	{ 
	    div.hide(); 
	    divDescription.hide();    
	    divSelectedInfo.hide();
	}
	
	//Update nav step
	if (selectedStep)
	{
	    $(currentView + selectedStep).show();
        $(currentView + selectedStep + 'Active').hide();
        $(currentView + currentStep).hide();
        $(currentView + currentStep + 'Active').show();
	}

    selectedStep = currentStep;
    selectedView = currentView;
	updatePrevNextButtons();  
	
	// show new panel;	
	$('div' + selectedStep).show();
	$('div' + selectedStep + 'Description').show();
	$('SelectedInfo_' + selectedStep).show();

	// *** this is where step-specific actions get called
	
	
	switch (currentStep) {
		case 'Mat':
			// need to be called here because won't work if mat panel is hidden
			enableMatPanel();
			break;
		case 'Frame': 
			// need to be called here because won't work if tab panel is hidden
			if (selectedNavPath == 'frame') {
				// frame panel always enabled in frame path
				enableFramePanel(true);
			} else {
				// rely on frame / no frame checkboxes
				enableFramePanel();
			}
			break;			
	}
    window.scrollTo(0,0);
}

// *** UPDATE PREV & NEXT BUTTONS -- all these function are used to determine whether a visible prev and next step exist and show/hide the prev/next buttons as needed
function goNext() {
    var nextStep = $(selectedView + selectedStep).next().next();

    if (nextStep.visible())
    	selectStep(nextStep);
    else 
    	selectStep(nextStep.next().next());
}
function goBack() {
    var prevStep = $(selectedView + selectedStep).previous().previous();
    if (prevStep.visible())
        selectStep(prevStep);
    else
    	selectStep(prevStep.previous().previous());
}
function updatePrevNextButtons() {
    var mode = $("getmode").value; 

    var nextStep = $(selectedView + selectedStep).next().next();
    
    if (mode.toLowerCase() != "gallerysetup")
    {
        if (nextStep != undefined && !nextStep.visible() && nextStep.next() != undefined) //may be hidden, so get next 
            nextStep = nextStep.next().next();
    }
	if (nextStep == undefined){
      	if ($F("brand") != "snapfish"){
          	$('frameshop_button_next').hide();
      	}else{
            $("nextButtonTop").hide();
            $("nextButtonBottom").hide();
        }
  	} else {
  	    if ($F("brand") != "snapfish"){
  	        $('frameshop_button_next').show();
      	}else{
            $("nextButtonTop").show();
            $("nextButtonBottom").show();
        }
        if (nextStep.id.endsWith('Cart') && nextStep.visible()) {
            if ($F("brand") == "snapfish"){
                $("nextButtonTop").hide();
                $("nextButtonBottom").hide();
            } else {
          	    $('frameshop_button_next').hide();
            }
        }
        if (nextStep.id.endsWith('Cart'))
          	$('frameshop_button_next').hide();
    }

    var prevStep = $(selectedView + selectedStep).previous().previous();
    if (prevStep != undefined && !prevStep.visible()) //may be hidden, so get next 
        prevStep = prevStep.previous().previous();

	if (prevStep == undefined){
    	if ($F("brand") != "snapfish"){
  	        $('frameshop_button_back').hide();
        }else{
            $("backButtonTop").hide();
            $("backButtonBottom").hide();
  	    }
  	} else {
      	if ($F("brand") != "snapfish"){
  	        $('frameshop_button_back').show();
        }else{  	
            $("backButtonTop").show();
            $("backButtonBottom").show();
  	    }
  	}
}




/***************** cropping *********************/
function EnableCustomCrop() {
    var crop_div = document.getElementById('custom_crop');
    if (crop_div) {
         crop_div.style.display = "block";
    }     
}

function ApplyCrop() {

    document.getElementById("custom_crop").style.display = "none";

    var x = document.getElementById('cropX').value;
    var y = document.getElementById('cropY').value;
    var w = document.getElementById('cropW').value;
    var h = document.getElementById('cropH').value;
    var imageW = document.getElementById('imageW').value;
    var imageH = document.getElementById('imageH').value;
    if (w == "" || h == "") {
        document.getElementById("cropLeft").value = 0;
        document.getElementById("cropTop").value = 0;
        document.getElementById("cropRight").value = 0;
        document.getElementById("cropBottom").value = 0;
    } else {
        var cropLeft = x / imageW;
        var cropTop = y / imageH;
        var cropRight = (imageW - x - w) / imageW;
        var cropBottom = (imageH - y - h) / imageH;
        document.getElementById("cropLeft").value = cropLeft;
        document.getElementById("cropTop").value = cropTop;
        document.getElementById("cropRight").value = cropRight;
        document.getElementById("cropBottom").value = cropBottom;
    }
     
    UpdateImageUrl();
    InitiatePricingUpdate();
    RequestServerSideValidation() ;
         
}

function $(id){return document.getElementById(id);}

function rollover(obj, src)
{
    $(obj.id).src = src;
}

function changeProductType()
{
    $('divChangeProduct').toggle();
    window.scrollTo(0,0);
}

function changeFrameshopProductType(page) 
{
    $('divChangeProduct').toggle();
    $('hdnChangeProductPage').value = page
}

function changeProductTypeContinue()
{
    if ($F('isMuseum') == 'true')
        window.location = "/ShowArtworkMuseum.aspx?imid=" + imid;
    else
    {
        if ($("brand").value == "snapfish")
            window.location = "/create/imageimport_snapfish.aspx?imid=" + imid + "&from=sa";
        else if ($("brand").value == "walgreens")
            window.location = "/create/imageimport_walgreens.aspx?imid=" + imid + "&from=sa";
        else if ($("brand").value == "smugmug")
            window.location = "/create/imageimport_smugmug.aspx?imid=" + imid + "&from=sa";
        else
            window.location = "/create/imageimportmember.aspx?imid=" + imid + "&from=sa";
    }
}



// ---------------------handle color chips begin ----------------------------//
function showColors(){
	document.getElementById("divSize").style.display="none";
	document.getElementById("divColors").style.display="block";
}
function hideColors(){
	document.getElementById("divSize").style.display="block";
	document.getElementById("divColors").style.display="none";
}

function selectColor(colorNum){
	document.getElementById("noWallColorText").style.display="none";
	document.getElementById("colorSelected").style.backgroundColor="#"+String(colorArray[colorNum]);
	document.getElementById("wall").style.backgroundColor="#"+String(colorArray[colorNum]);
	document.getElementById("smallwall").style.backgroundColor="#"+String(colorArray[colorNum]);
}

// -------------------------handle color chips end --------------------------//

var retryAttempt = 0;
function GetFramedThumb(that, galleryid, imid, maxWidth, maxHeight, materialID)
{
    if (Util.getElementByEndingId("img", "largeImage").src == "http://www.imagekind.com/images/banners/missing_image.gif")
    {
        that.src = "http://www.imagekind.com/images/banners/missing_image.gif";
        return;
    }

    new Ajax.Request('/services/frame_engine_save.ashx', {method:'get', parameters: {IMID: imid, maxWidth: 150, maxHeight: 150, materialID: materialID }}); 

    var tryURL = that.src;
    if(tryURL.indexOf('?') == -1)
        tryURL += '?1'
    else
        tryURL += '&1'

    if(typeof(that.style.maxHeight) != 'undefined')
    {
        that.style.maxHeight = maxHeight;
        that.style.maxWidth = maxWidth;
    }
    that.src = "http://d3br5i6ykfuol.cloudfront.net/showartwork/loading.gif";
    if (retryAttempt <= 3)
        window.setTimeout(function(){if(/loading/.test(that.src)) { that.src = tryURL; retryAttempt += 1;} },1000)
    else
    {
        if (imid.indexOf('_' == -1))
            that.src = "http://thumbs.imagekind.com/member/" + galleryid + "/uploadedartwork/150X150/" + imid + ".jpg";
        else
            that.src = "http://thumbs.imagekind.com/museum/150X150/" + galleryid + "/JPGS/" + imid + ".jpg";
    }
 }



