﻿// JScript File
// Designed for /shop/albums/default.aspx and /shop/accessor/default.aspx pages

/**
 * album pages Functions
 */

function closeenlgdiv() {    
	hidediv("enlgdiv");
	hidediv("pageDimmer");	
}

function showenlgdiv() { 
    dimPage();	
	showdiv("enlgdiv");
}

function DisplayEnlgImg(img){
    	showdiv("enlgloading");
    	showenlgdiv();
    	getId("enlgimg").src = "";
    	getId("enlgimg").src = img.src.replace("m_","l_"); 
    	replaceMissingImages(getId("enlgimg"), '/images/products/l_defimg.jpg');
    	waitUntil("!getId('enlgimg').complete", "finishEnlg()", 200)
    	
}

function finishEnlg()
{
    centerDiv("enlgdiv");
    hidediv("enlgloading");
}



function switchPreview(imgsrc){
         getId("mainpic").src = "/images/share/loading.gif";
            
        if (imgsrc == "giftbox") //handle giftbox preview
            getId("mainpic").src = "/images/share/m_giftbox.jpg";
        else        
            getId("mainpic").src = imgsrc.src.replace(/t_/i,"m_");  
            
        getId("mainpic").alt = "click to enlarge";
        getId("mainpic").title = "click to enlarge";
        replaceMissingImages(getId("mainpic"), '/images/products/m_defimg.jpg');
}


var prods = new Array();  
var skus = new Array();  
var oldqty = 1;
var attrsku = "";

//Holds all the product attrs
 function prod(prodName, ProdGrpID, attr, desc, prodline) {
  this.prodName = prodName;
  this.ProdGrpID = ProdGrpID;
  this.attr = attr;
  this.desc = desc;
  this.prodline = prodline;
}

// adds product to the "prods" array
function addprod(prodName, ProdGrpID, attr, desc, prodline){
  prods.push(new prod(prodName.replace("()", ""), ProdGrpID, attr, desc, prodline)); 
}

//loads all the products from the "prods" array to the "productList" drop down
function loadProds(){

 var dropdownlist = getId("ProductList");
  for (var j = 0; j < prods.length; j++) {  
      addOption(dropdownlist, prods[j].prodName, prods[j].ProdGrpID); 
      }       
}

// Holds all the SKU attrs
 function sku(prod, sk, col, price, siz, prdgrpid) {
  this.prod = prod;
  this.sk = sk;
  this.col = col;
  this.siz = siz;
  this.price = price;
  this.prdgrpid = prdgrpid;
}

//adds a sku to the "skus" array
function addsku(prod, sk, col, price, siz, prdgrpid){
          skus.push(new sku(prod, sk, col, price, siz, prdgrpid));
}


// handles "ProductList" dropdown onChange event (Default.aspx)
function updateselection()
{
    var selectedProd = getId("ProductList").value;
    var dropdownlist = getId("ColorList");
    dropdownlist.length=0;//reset color list dropdown
    addOption(dropdownlist, 'choose color', '');
    
    //get prod line desc and set it for display
    for (var j = 0; j < prods.length; j++) {
        if (prods[j].ProdGrpID == selectedProd){
        getId("ProdDescText").innerHTML="<br><br><font class='prodSubTitle'>"+prods[j].prodName+"</font><br><br>"+prods[j].desc;
        attrsku=prods[j].attr;
        }
    }
    

    
    //if product selected, load/display swatches
    //Show: Color list, Quantiy box, Swatch Images, gift box option (if available)
    //Hide: Detail images
    if (getId("ProductList").selectedIndex != 0) 
    {
        hidediv("ProdListText");
        hidediv("ProdLineDescText");
        hidediv("swatchPreview");
        hidediv("detailImgs");
        
        showdiv("ColorListDiv");
        showdiv("qtydiv"); 
        showdiv("SwatchImgs");
        showdiv("ProdDescText");
        showdiv("cartbutton"); 
        showdiv("resetbutton"); 
      
        getId("actiondiv").style.top = "254px";
        // display review section + load swatches for the selected product
        review();
        loadSwatches(); 
    }
    //if NO product selected 
    //Show: Detail images
    //Hide: Color list, Quantiy box, Swatch Images, review section
    else
    {
        hidediv("ColorListDiv");
        hidediv("qtydiv");
        hidediv("review");
        hidediv("SwatchImgs");
        hidediv("cartbutton"); 
        hidediv("cartbuttonoff");
        hidediv("ProdDescText");
        hidediv("resetbutton");
        hidediv("giftbox");
        
                
        showdiv("detailImgs"); 
        showdiv("ProdLineDescText");
        showdiv("ProdListText");
        showdiv("swatchPreview");
        
        getId("actiondiv").style.top = "410px";
    }
    
    // add all the available colors for the selected product
    for (var j = 0; j < skus.length; j++) {
        if (skus[j].prdgrpid == selectedProd)
            addOption(dropdownlist, skus[j].col, skus[j].sk);   
    }
}

// displays/Updates "YOUR SELECTION:" (product review) div
function review()
{
    if (!checknumber(getId("qtybox").value))
    {
       alert("Please enter a valid number!");
       getId("qtybox").value = oldqty;
    }

    if (getId("qtybox").value < 1)
    {
        alert("Quantity has to be 1 or more!");
        getId("qtybox").value = oldqty;
    }

    oldqty = getId("qtybox").value;

    //populate review data
    var reviewdata= "<font class='prodSubTitle'>YOUR SELECTION:</font> " +
    "<img src='/images/share/spacebox.gif' height='20' align='top'/><br />";
  
    reviewdata=reviewdata+"<b>"+getId("ProductList").options[getId("ProductList").selectedIndex].text+"</b>";

    for (var j = 0; j < skus.length; j++) {
        if (skus[j].sk  == getId("ColorList").value){
	        
	        showdiv("cartbutton"); 
            hidediv("cartbuttonoff"); 
            
            data = GetSkuData(getId("ColorList").value, getId("qtybox").value);
	       
            reviewdata=reviewdata+data;
            reviewdata=reviewdata+"<br />"+skus[j].col;
            reviewdata=reviewdata+"<br />#"+skus[j].sk; 

            break;        
        }
    }
    reviewdata=reviewdata+"<br />Quantity: "+getId("qtybox").value;
    // if no color is selected yet, hide "add to cart" button div
    if (getId("ColorList").selectedIndex == 0){
        hidediv("cartbutton"); 
        hidediv("giftbox"); 
        showdiv("cartbuttonoff"); 
    }
    // otherwise, if color selected, update form for miva 
    //and show "add to cart" button div
    else {
     //if (attrsku != "" && attrsku != "700-3105" && attrsku != "700-3145")
     //{
     //   showdiv("giftbox");
     //   showdiv("giftbox");
     //}
        //showdiv("cartbutton");  
       // hidediv("cartbuttonoff");      
    }
    //write and display review data
    getId("reviewdata").innerHTML = reviewdata;
    showdiv("review");
    
   
}

//handles "ColorList" dropdown
function updateSwatch()
{   
    //if a valid color selected
    if (getId("ColorList").selectedIndex != 0){
    var imgloc = getId("ProductList").value;
    getId("mainpic").src = "/images/products/" + productLine + "/" + imgloc + "/m_" +
                            getId("ColorList").value.replace("t_","m_") + ".jpg"; 
    replaceMissingImages(getId("mainpic"),'/images/products/m_defimg.jpg');
     }
     
    // display and update product selection 
    review();
}

//handles swatch rollover
function previewSwatch(img)
{       
    getId("mainpic").src = '/images/share/loading.gif';
    getId("mainpic").src = img.src.replace("t_","m_"); 
    replaceMissingImages(getId("mainpic"),'/images/products/m_defimg.jpg');
}

//get and display all the swatches for the selected product
function loadSwatches()
{
    showdiv("SwatchImgs"); 
    getId("SwatchImgs").innerHTML = "<img src='/images/share/loading.gif'/>";
    var mainImg="";    
    var swatches = "<table cellpadding='0' cellspacing='0'>" +
     //"<tr><td><img src='/images/share/spacebox.gif'/></td><td>" +
     //"<img src='/images/share/color_swatches.jpg'></td></tr>"+
     "<tr><td colspan='2'><table cellpadding='1' cellspacing='2'><tr>";
    var selectedProd = getId("ProductList").value;
    var totProdSwatches = 0, swatthisrow=0;
    
    for (var j = 0; j < skus.length; j++) {
        if (skus[j].prdgrpid == selectedProd){
                mainImg="/images/products/"+ productLine + "/"+ skus[j].prdgrpid + "/t_" + skus[j].sk + ".jpg";                     
                swatches = swatches + "<td width='34'><img height='34' width='34' alt='"+skus[j].col+"' title='"+skus[j].col+"' src='"+ mainImg + "' onclick='javascript:pickColor(this,\""+skus[j].sk+"\");' onmouseover='previewSwatch(this);' style='cursor:pointer;'></td>"
                swatthisrow++;
                if (swatthisrow%8 == 0)
                 swatches = swatches + "</tr><tr>"
        }
    }
    swatches = swatches + "</td></table></tr></table>"    
    getId("SwatchImgs").innerHTML = swatches;
    getId("mainpic").src = mainImg.replace(/t_/i,"m_");
    replaceMissingImages(getId("mainpic"), '/images/products/m_defimg.jpg');  //pre load  
    ReplaceBrokenImages("SwatchImgs", '/images/products/t_defimg.jpg'); //post load
}

// handles swatch onClick event
// updates mainImg and the colorlist dropdown
function pickColor(img, selectedSKU){
    var SelProdGrp = getId("ProductList").value; 
    var color = 1;
        for (var j = 0; j < skus.length; j++) { 
            //if sku found, use 'color' as index
            if (skus[j].sk  == selectedSKU){
                getId("ColorList").selectedIndex = color; 
                break;
            }     
            //if prod group found increment color    
            if(skus[j].prdgrpid  == SelProdGrp){ 
                currentProd = skus[j].prdgrpid; 
                color++;
            } 
                 
        }
    review();
    switchPreview(img);    
  
}

// handles product list onClick event 
// updates mainImg and the colorlist dropdown
// used auto-load a size after page is loaded
function pickSize(selectedSize){
            for (var j = 0; j < prods.length; j++) { 
                if (prods[j].ProdGrpID  == selectedSize){
                getId("ProductList").selectedIndex = j+1;
                updateselection(); 
                break;
                }                  
            }
}
function pickSku(sku){
         GetUpdateSize(sku);
         for (var j = 1; j < getId("ColorList").length; j++) { 
                if (getId("ColorList").options[j].value  == sku){
                getId("ColorList").selectedIndex = j;
                updateSwatch();
                break;
                }                  
            }
}
function GetUpdateSize(sku){
         for (var j = 0; j < skus.length; j++) { 
                if (skus[j].sk  == sku){
                pickSize(skus[j].prdgrpid);
                break;
                }                  
            }
}

function argiftbox()
{
    if(getId("giftboxckbx").checked){
       getId("attrcount").value=1;
       getId("gboxsku").value=attrsku;       
       }
    else
       getId("attrcount").value=0;
}

function updateAttr(count, comments)
{
    getId("attrcount").value=count;
    comments=comments.replace('Availability: <font color=\"red\">'," ");
    comments=comments.replace("</font>","");
    getId("comments").value=comments;
}



function resetForm()
{
    getId("ProductList").selectedIndex = 0;
    updateselection();
}

function AddToCart()
{
    //if not enough stock DO NOT proceed
    dimPage();
    showdiv("cartdiv");    
    div = getId("cartdivcntnt")
    div.innerHTML = '<img src ="/images/share/loading.gif" id="cartloading"><br>';
    div.innerHTML += '<div id="cartstat">adding your item to cart, please wait...</a>';
    centerDiv("cartdiv"); 
    //wait until cartloading element is displayed
    waitUntil("getId('cartloading') != null", 'procAddCart()', 200)
   
    
}

function procAddCart()
{
    div = getId("cartdivcntnt")
     var attrcount = 0;     
    if(getId("giftboxckbx").checked)
       attrcount=1;
    
    data =  "&" + "Action=ADPR&Screen=BASK&Store_Code=K";
    data += "&" + "Product_Code=" + getId("ColorList").value; 
    data += "&" + "Quantity=" + getId("qtybox").value;
    //data += "&" + "Product_Attributes[1]:code=giftbox";
    //data += "&" + "Product_Attributes[1]:template_code="+ attrsku;
    //data += "&" + "Product_Attributes[1]:value=Gift Box";
    //data += "&" + "Product_Attribute_Count=" +  attrcount;
    
    //dev server url
    //url = "/shop/products/?";  
    
    //live URL
    url = "http://kolo.com/mm5/merchant.mvc?&addpid="+ getId("ColorList").value + data;    
   
    var d = new Date();  
    url = url + "&t=" + d.getTime(); 
    ajxResponse = "200";    
    ajxResponseStr = getDataSync(url); 
    if(ajxResponseStr.match("KOLO: Sold Out") == "KOLO: Sold Out")
    	ajxResponse = "413";
    if(ajxResponseStr.match("KOLO: Limited Stock!") == "KOLO: Limited Stock!")
    	ajxResponse = "414";
    div.innerHTML = upsell(getId("ColorList").value, ajxResponse)        
    centerDiv("cartdiv"); 
    
    updatePresCart();
}

function closecartdiv()
{
    hidediv("cartdiv");
	hidediv("pageDimmer");	
}

function upsell(sku, status)
{
    var d = new Date(); 
    data = "&" + "sku=" + sku; 
    data += "&" + "status=" + status;
    data += "&" + "qty=" + getId("qtybox").value; 
    data += "&" + "gb=" + getId("giftboxckbx").checked; 
    url = "/shop/upsell/?"+data;      
    url = url + "&t=" + d.getTime();    
    return getDataSync(url);    
}

/**
 * acc Functions
 */
 
 //loads all the products from the "prods" array to the "productList" drop down
function loadAccs(actprodid){
  var dropdownlist = getId("ProductList"+actprodid);
  for (var j = 0; j < prods.length; j++) {  
    if (prods[j].prodline == actprodid)
      addOption(dropdownlist, prods[j].prodName, prods[j].ProdGrpID); 
      }       
}

function updateAccSel(actprodid)
{
    var selectedProd = getId("ProductList"+actprodid).value;
    var dropdownlist = getId("ColorList"+actprodid);
    dropdownlist.length=0;//reset color list dropdown
    addOption(dropdownlist, 'choose color', '');

    //disable add to cart for all items and reset all combo boxes.
    var prodlines=getId("ProductLines").value;
    prodlines=prodlines.split(";"); 
    for(var i=0; i<prodlines.length; i++)
    {
        getId("cartbutton"+prodlines[i]).style.display="none";
        getId("cartbuttonoff"+prodlines[i]).style.display="block";
        getId("ColorList"+prodlines[i]).selectedIndex = 0;
        if (prodlines[i] != actprodid) //if this productLine is not the same as one in use
        {
            getId("ProductList"+prodlines[i]).selectedIndex = 0;
            getId("ColorList"+prodlines[i]).length= 0;
            addOption(getId("ColorList"+prodlines[i]), 'choose size', '');
            getId("ProdDescText"+prodlines[i]).innerHTML=getId("dfltProdDescText"+prodlines[i]).value;
        }
        
    }   
 
    //get prod line desc and set it for display
    for (var j = 0; j < prods.length; j++) {
        if (prods[j].ProdGrpID == selectedProd){
        getId("ProdDescText"+actprodid).innerHTML=prods[j].desc;
        attrsku=prods[j].attr;
        break;
       }
       else 
        getId("ProdDescText"+actprodid).innerHTML=getId("dfltProdDescText"+actprodid).value;
    }
 
    //add all the available colors for the selected product
    for (var j = 0; j < skus.length; j++) {
        if (skus[j].prdgrpid == selectedProd)
            addOption(dropdownlist, skus[j].col, skus[j].sk);   
    }
}
  
//handles ACC "ColorList" dropdown 
function updateAccCol(actprodid)
{   
   var selectedSku = getId("ColorList"+actprodid).value;
   getId("Quantity").value = "0";
   getId("Product_Code").value = "";
    //if a valid color selected
    if (getId("ColorList"+actprodid).selectedIndex != 0){
           //update from
           document.myform.action = "http://kolo.com/mm5/merchant.mvc?&addpid="+selectedSku;
           getId("Quantity").value = getId("qtybox"+actprodid).value;
           getId("Product_Code").value = selectedSku;
           //hide grey add to cart img
           getId("cartbuttonoff"+actprodid).style.display="none";
           //show add to cart button
           getId("cartbutton"+actprodid).style.display="block";
     }
     
}
function updateAccQty(actprodid)
{   
    checknumber("qtybox"+actprodid);
    newqtyBox=getId("qtybox"+actprodid);
    if (newqtyBox.value < 1)
    {
        alert("Quantity has to be 1 or more!");
        newqtyBox.value = oldqty;
    }
    oldqty = newqtyBox.value;
    getId("Quantity").value = newqtyBox.value;
}

/**
Common Product Functions
**/
function handleAjxStatChg()
{
    if(getId('stockstatus').innerHTML.match("backorder") != null)
        updateAttr('2', getId('stockstatus').innerHTML);
    else
        updateAttr('1', '')
}

//gets inventory levels, price, name given sku and qty using ajax
function GetSkuData(sku, qty){  

     var ajxResponse;  
     var stockstatdiv = document.getElementById('stockstatus'); 
     var data = "";
     
     if(sku != ""){       
            var requestURL = '/shop/stock_status/stockstatus.php';            
            var url = requestURL + "?sku=" + sku + "&qty=" + qty;
		    var d = new Date();  		    
            url = url + "&t=" + d.getTime(); //Uncache URL    
			stockstatdiv.innerHTML = "Availability: checking stock..."
            
            ajxResponse = getDataSync(url);
            mydata = ajxResponse.split(";");
            
            
            if (ajxResponse.match("code") == null) //if an error was returned, dont display the price
            {
                if (mydata[2] > 0) //cost field in miva
				    data=data+": <b><S>$"+mydata[2]+" </S><font color=red>$"+mydata[1]+" ea. special</b></font>";
                else
                    data=data+": <b>$"+mydata[1]+" ea.</b>";
            }
            else
            {
	            showdiv("cartbuttonoff");
	            showdiv("cartbuttonoff"); 
                hidediv("cartbutton");
            }
       }
      else
        ajxResponse = ""
        stockstatdiv.innerHTML  = mydata[0];	
        if (mydata[3] == "0")
        {
            showdiv("cartbuttonoff");
            showdiv("cartbuttonoff"); 
            hidediv("cartbutton");
        }            
       
     return data;

}


