﻿// JScript File
// Designed for /shop/albums/default.aspx and /shop/accessor/default.aspx pages

/**
 * album pages Functions
 */
var loadingMSG = "<img border='0' src='/images/share/loading.gif'><br>Loading....";
var pages = TotPages = AID = 0;

function DisplayEnlgImg(img){
    $('#dialog-content').html(loadingMSG);
    $("#popup-dialog").dialog("option", {title: "", height: 635, width: 620 });
    $("#popup-dialog").dialog("open");
    $('#dialog-content').html("<img id='enlgimg' src='"+img.src.replace("m_","l_")+"'>");
    replaceMissingImages(getId("enlgimg"), '/images/products/l_defimg.jpg');	
}

function switchPreview(imgsrc) {
    //check video
    filen = getFileName(imgsrc.src).replace(/.jpg/i, "");
    if (filen.indexOf("_vid_") < 0) {
        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');
    }
    else 
        showVideo(filen);
}

function writeReview() {
    $('#dialog-content').html(loadingMSG);
    $("#popup-dialog").dialog("option", { title: "Review Product", height: 620, width: 614});
    $("#popup-dialog").dialog("open");
    $.ajax({
        url: "/shop/reviews/index.php?action=write&pl="+plid,
        success: function (data) {
            $('#dialog-content').html(data);
            $('#dialog-content :radio.star').rating();
        }
    });
}

function submitReview() {
    tipsDiv = $(".validateTips");
    var bValid = true,
    review_review = $("#review_review"), review_title = $("#review_title"), display_name = $("#display_name"),
    allFields = $([]).add(review_review).add(review_title);
    allFields.removeClass("ui-state-error");
    bValid = bValid && checkLength(display_name, "Display Name", 4, 60);
    bValid = bValid && checkLength(review_title, "Review Title", 4, 60);
    bValid = bValid && checkLength(review_review, "Review Comment", 25, 1500);
    if (bValid) {
        allFields.removeClass("ui-state-error");
        $.post("/shop/reviews/index.php?action=insertReview&pl=" + plid,
                { userid: $('#review_userid').val(),
                    display_name: $('#display_name').val(),
                    recom: $('#review_recom').val(),
                    star_rating: $('input:radio[name=review_rating]:checked').val(),
                    review_comment: $('#review_review').val(),
                    review_title: $('#review_title').val()
                })
        .success(function (data) {
            //if (data=="1") {
                $("#popup-dialog").dialog("close");
            //    alert("Your review has been submitted successfully. It will be visible on the site once it has been approved. Thank you.");
            //}
            //else 
				alert(data);
        })
        .error(function () { alert("error"); });
    }
}

function enumReviews(pid, pageno) {
    $('#review-data').html("<p style='height:630px;'>"+loadingMSG+"</p>");
    $.ajax({
        url: "/shop/reviews/enumReviews.aspx?pl=" + pid + "&pg=" + pageno,
        success: function (data) {
            $('#review-data').html(data);
            $('#review-data :radio.star').rating();
        }
    });
   
}

function showVideo(filename) {
    var d = new Date();
    vars = "&" + "id=" + filename.replace(/t_vid_/i, "");
    $('#dialog-content').html(loadingMSG);
    $("#popup-dialog").dialog("option", { title: "", height: 470, width: 695 }); ;
    $("#popup-dialog").dialog("open");
    $.ajax({
        url: "/video/?" + vars,
        success: function (data) {
            $('#dialog-content').html(data);
        }
    });
    }


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;
           //getId("ProdDescText").innerHTML += "<br><a href='javascript:void(0);' onClick='javascript:DisplaySpec()'><span style='color: rgb(255, 153, 51);'>Detailed Specifications</span></a>";
        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 != "")
     {
        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='1' cellspacing='1'>" +
     //"<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='1'><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()
{
}

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 DisplaySpec() {
    var d = new Date();
    vars = "&" + "prodgrpid=" + getId("ProductList").value;
    $('#dialog-content').html(loadingMSG);
    $("#popup-dialog").dialog("option", { title: "", height: 175, width: 400 }); ;
    $("#popup-dialog").dialog("open");
    $.ajax({
        url: "/shop/prodspecs/?" + vars + "&t=" + d.getTime(),
        success: function (data) {
            $('#dialog-content').html(data);
        }
    });
}

//handles photo books?
function AddSkuToCart(sku, isBook)
{
    $('#dialog-content').html(loadingMSG);
    $("#popup-dialog").dialog("option", { title: "", height: 175, width: 400 }); ;
    $("#popup-dialog").dialog("open");
    procAddCart(sku, isBook);
}
function AddToCart() {
    $('#dialog-content').html(loadingMSG);
    $("#popup-dialog").dialog("option", { title: "", height: 175, width: 400 }); ;
    $("#popup-dialog").dialog("open");
    procAddCart(getId("ColorList").value, false);
}

function procAddCart(sku, isBook)
{
    ajxResponse = "200";
    url = "/cart/index.php?route=module/cart/callback&"; //live URL     
   
    if((getId("giftboxckbx").checked) && (!isBook))
    {
        pid=getCartPid(attrsku);
        data = "quantity="+getId("qtybox").value+"&product_id="+pid;
        var d = new Date();              
        ajxResponseStr = postDataSync(url + "&t=" + d.getTime(), data); //add giftbox   
	}
    
    pid=getCartPid(sku);
    data = "quantity="+getId("qtybox").value+"&product_id="+pid;    
    if(isBook) data += "&option[1]="+TotPages+"&option[2]=AID-"+AID;
    var d = new Date();     
    ajxResponseStr = postDataSync(url + "&t=" + d.getTime(), data); 
   
    //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)
    $('#dialog-content').html(upsell(sku, ajxResponse));

    $("a[rel='contShopping']").bind('click.', function (e) {
            e.preventDefault();
            $("#popup-dialog").dialog("close");
    });     
    
    //report cart addition to omniture
	s.linkTrackVars="products,events"; 
	s.linkTrackEvents="scAdd";
	s.events="scAdd";
	s.products=";"+sku;
	void(s.tl());
	
	//update pres cart display
    updatePresCart();
}

function getCartPid(sku)
{
    pidurl = "/cart/utilities/getcartprodid/?sku="+sku
    var d = new Date();  
    pidurl = pidurl + "&t=" + d.getTime(); 
    return getDataSync(pidurl); 
}


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;

}



