﻿var _BROWSER;
var _OS;
var _BROWSERVERSION;
$(function() {
    
    _BROWSER = $.client.browser;
    _OS = $.client.os;
    _BROWSERVERSION = $.client.version;


 
    // homepage slider content adjustments to slides
    $("div.slide-container div.contentBox-inner").children().css('margin-top','-5px');
    if (_OS == 'Windows' && _BROWSER == 'Explorer' && _BROWSERVERSION < 8) {
        $("#contentBox").css('margin-top','110px');
    
        $("div.slide-container div.contentBox-inner").children().css({
            'margin-top':'-5px', 
            'margin-left':'0px'
        });
    }
    else if(_BROWSER == 'Explorer'){
        $('#footer a').css({'vertical-align':'bottom'});
    }
    else{
        // fix to shift contentBox-inner children up 15px 
        //$("div.contentBox-inner").children().css({'top':'-15px','position':'relative'});//does not work in ie7
    }

    // last in order, so we get the heights from added items also
    $("#liveArea").prepend('<div class="leftfade"></div><div class="rightfade"></div>');
    //$(".leftfade, .rightfade").css({height: $(document).height()});
    $(window).resize();
});
$(window).load(function(){
    $(window).resize();
    getCart(false);
});

$(window).resize(function(){
    rectifyfadesFooter();
});
function rectifyfadesFooter(){
    //var fpos = $('#footer').offset().top;
    var dheight = $(document).height();
    var wheight = $(window).height();
    if( wheight >= dheight - 10 ){
        $('#footer').css({position:'absolute',bottom:0});
    }
    else{
        $('#footer').css({position:'relative',bottom:'inherit'});
    }
    $(".leftfade, .rightfade").css({height: $('#footer').offset().top});
}


// navigational dropdown handler, ddsmoothmenu.js, ddsmoothmenu.css
// note: ddsmoothmenu.js must be loaded before init.js
ddsmoothmenu.init({
     mainmenuid: "smoothmenu1", //menu DIV id
     orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
     classname: 'ddsmoothmenu', //class added to menu's outer DIV
     contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
});



$(document).ready(function(){
    //setup onclick for homepageNesletter
    $('#homepage_newsletterbtn').click(onNewsletterSignup);
    $('.homepage_contestBtn').click(function(){encase('/homepagePopup.aspx',725,555);});
    
}) 

$.fn.scrollableAddClones = function(addItems) {
  // grab scrollable plugin
  var scrollable;
  if (!(scrollable = $(this).data('scrollable')) || !scrollable.getConf().circular)
    return;
  // grab scrollable elements and remember it's count
  var nodes = scrollable.getItems();
  var length = nodes.length;
  // grab class for the nodes
  var clonedClass = scrollable.getConf().clonedClass;
  // get wrap object to append the clones to
  var wrap = scrollable.getItemWrap();
  // fill as much nodes as needed for 500 pixels
  if (!addItems) addItems = Math.ceil(500 / nodes.eq(1).width());
  // create fake container to add the clones to (max 15 clones)
  var newNodesAppend = $('<span />');
  for (var i = 1; i <= (addItems < 15 ? addItems : 15); i++)
    nodes.eq(i % length).clone().addClass(clonedClass).appendTo(newNodesAppend);
  // insert HTML
  newNodesAppend.children().appendTo(wrap);
}

// Windows renders custom fonts very badly, so we disable them.
/*if (/win/i.test(navigator.platform)) {
  $(window).load(function() {
    if (!document.styleSheets) { return; }

    for (var i = 0; i < document.styleSheets.length; i++) {
      var sheet = document.styleSheets[i];
      var rules = sheet.cssRules || sheet.rules;
      var fontRules = [];
      for (var j = 0; j < rules.length; j++) {
        var rule = rules[j];
        if (rule.type == 5) {  // @font-face rule
          fontRules.push(j);
        }
      }
      for (var j = fontRules.length - 1; j >= 0; j--) {
        if (sheet.deleteRule) {
          sheet.deleteRule(fontRules[j]);
        } else if (sheet.removeRule) {
          sheet.removeRule(fontRules[j]);
        }
      }
    }  
  });  
}*/


var destroy_encaseerror;
if(!destroy_encaseerror){
    destroy_encaseerror = function destroy_encaseerror(){ $("#encaser.encaseerror").hide().remove(); }
}

$('.errorDisplay').live({
    mouseover:function(){
    if( $(this).text().length > 90 )
        encaseerror({title:'',error:$(this).text(),offsetDOM:$(this),offsetAdd_Top:-120, offsetAdd_Left:-220 , large_tooltip:true });    
    else
        encaseerror({title:'',error:$(this).text(),offsetDOM:$(this),offsetAdd_Top:-70, offsetAdd_Left:-220 , tooltip:true });
    },
    mouseout:destroy_encaseerror
});

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

var dlog = function(item){
    if(window.console) {
        if(window.console.firebug != '') console.info(item);
        else console.log(item);
    }
}


function onNewsletterSignup(){
    var email = $("#footer .jq-newsletteremail").val();
    $.ajax({ url:'/ajx/_email_signup.aspx', type:'POST', dataType:'json', data:{Uid:email,mode:1}, cache:false }) 
        .success( onNewsletterResponse )
        .error( function(e){dlog('error'+e)}); 
    return false;
}

function onNewsletterResponse( data ){
    dlog(data);
    var d = data.UPDATE_RESULT;
    if(d.RESULT == "SUCCESS")
         window.location.href = '/email_signup.aspx';//encaseerror({ error:'Email Successfully Added!.', offsetDOM:$('#homepage_newsletterbtn'), offsetAdd_Top:-80, offsetAdd_Left:-200, tooltip:true,nored:true });
    else{
        var err = d.ERRORS[0];
        encaseerror({ error:err, offsetDOM:$('#homepage_newsletterbtn'), offsetAdd_Top:-80, offsetAdd_Left:-200, tooltip:true });
    }
    setTimeout( destroy_encaseerror , 1500)
}

// ------------------------------------------------------------------------------------------------------------------------------------------------------------
//USer Interface Helper Functions
function iface_disableBtn( opt ){
    //dlog('disabling btns');dlog(opt);
    if( opt.text )
        opt.$Dom.addClass('inverted').addClass('disabled').removeClass('button').text( opt.text );
    else
        opt.$Dom.addClass('inverted').addClass('disabled').removeClass('button');
    
}

function iface_enableBtn( opt ){
    //dlog('enabaling btns');dlog(opt);
    if( opt.text )
        opt.$Dom.removeClass('inverted').removeClass('disabled').addClass('button').text(opt.text);
    else
        opt.$Dom.removeClass('inverted').removeClass('disabled').addClass('button');
}





//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//ShopBag Functions
var g_bagTimeoutID;
function getCart(showAfterLoad){//just get the cart
            
    $.ajax({ url:'/ajx/_addTocart.aspx', type:'POST', dataType:'json', cache:false }) 
        .success( iface_buildShopBag )
        .success( function(d){ if(showAfterLoad) showShopBag(); })
        .error( function(e){dlog('error'+e)}); 
   return true;
}


function showSubNav( params ){
    $('#home_shopBag .bag_overview').show();
    if(params.subNavID!= null){
       	var btnOset = params.btnID.offset();
       	params.subNavID.css( {display : 'block',top:params.top , right: params.right });
	}
};


$(document).ready(function (){
    var homeShopBag =  '   \
    <div id="home_shopBag" class="shop_bag smBlueHelv" style="width: 300px;">\
        <div class="column last" style="width: 278px; height: 450">\
            <!-- cart overview  -->\
            <div class="bag_overview span-7 last" style="padding: 4px; background-color: #FFFFFF;">\
                <div class="span-3">\
                    <a href="/checkout.aspx"><h2 class="TGoth regularkern">Shopping Bag </h2></a>\
                </div>\
                <div class="span-4 last" style="padding-top:2px;">\
                    <p class="min-margin home_bagItems" style="line-height: 12px;">No Items in your cart</p>\
                    <p class="min-margin home_bagPrice" style="line-height: 12px;">$0.00</p>\
                </div>\
                <div class="span-7  last">\
                    <p class="min-margin allcaps home_bagMsg"></p>\
                </div>\
            </div>\
            <!-- list of all items -->\
            <div class="column bag_list last  clear"></div>\
            <!-- end dynamic list -->\
            <div class="column last clear" style="padding: 4px 2px 4px 2px; width:274px; background-color: #FFFFFF;">\
            <div class="span-7" style=" "><a class="TGoth buttonLink " href="/checkout.aspx">VIEW BAG </a> <a class="TGoth buttonLink right" href="/checkout.aspx"> CHECKOUT</a></div> \
            <\div>\
        </div>\
        <!-- end shopping_bag -->\
    </div>\ ';
        
    var $shpbag = $(homeShopBag).hover( function() { 
        if( (typeof g_bagTimeoutID == "number") )
            window.clearTimeout(g_bagTimeoutID);
        showShopBag();
    },
    function(){
        g_bagTimeoutID = removeSubNav( { timeout:g_bagTimeoutID , subNavID:$('#home_shopBag') , effect:'slide' } );
    });

    $('#header-center').append($shpbag);
});


function removeSubNav( params ){
    if(params.subNavID!= null){
        params.timeoutID = window.setTimeout(
            function(){         
                params.subNavID.hide();
            }, 
            50);
        return params.timeoutID;
    }

};


function showShopBag(){

    showSubNav( { btnID:$('#shopbag_btn') , subNavID:$('#home_shopBag') , top:22 , right:12 , effect:'slide' } );
   
    //$('#home_shopBag .scrollme ').jScrollPane();
    if( (typeof g_bagTimeoutID == "number") ){
        window.clearTimeout(g_bagTimeoutID);//comment for new
    }
}

function iface_buildShopBag( bInfo ){ 
    //dlog(bInfo);
    iface_clearShopBag();
    if( bInfo.results.length ){

        
        var ts = $('<div>');
        $.each(bInfo.results,function(i,val){
            //dlog('about to build with this image '+val.IMAGE);
            ts.append( iface_buildShopBagItem(val) );
        });

        $('#home_shopBag .bag_list').html(ts).css({width:'100%'});
        $('.home_bagItems','#home_shopBag').text(bInfo.ItemCount + ' items in your cart');
        $('.section4').html('');
        if( bInfo.ItemCount > 1  )
            $('.section4').html(bInfo.ItemCount+' items');
        else if( bInfo.ItemCount == 1  )
            $('.section4').html(bInfo.ItemCount+' item');
        $('.home_bagPrice','#home_shopBag').text(bInfo.Total);
        $('#home_shopBag div.bag_list').show();
           // $('#home_shopBag .scrollme ').jScrollPane();
        
    }

    else{
        //dlog('NO ITEMS IN CART');
        iface_clearShopBag();
    }
}

function iface_clearShopBag(){
    //dlog('reseting shoppingbag');
    $('#home_shopBag .bag_list').html(); //clear items out of the shopping bag
    $('.home_bagItems','#home_shopBag').text('0 items in your cart');
    $('.home_bagPrice','#home_shopBag').text('$0.00');
    $('div.bag_product','#home_shopBag').remove(); //clear items out of the shopping bag
    $('#home_shopBag div.bag_list').hide();
}



function iface_buildShopBagItem( itemInfo ){ 
    //dlog('------ building shopping bag');
    var $newItem = $('<div class="column last bag_product" style="width: 100%;"><div class="button column" style="width: 50px;"><img class="home_itemImg" src="" height="50px" width="50px" /></div> <div class="button column" style="width: 130px;"><h4 class="tight strong home_itemBrand"></h4><p class="tight home_itemName" style="height: 34px;"></p><p class="small nomargin home_itemAux">size: <span class="shoppingBagItem_size"></span> | <span class="shoppingBagItem_color"></span> </p></div><div class="column last" style="width: 60px;"><p class="min-margin small closebtn button" style="margin-bottom: 10px; text-align: right;">remove</p><p class="home_itemQty" style="margin: 0;"> <span class="shoppingBagItem_qty"> x  </p><h4 class="home_itemPrice" style="text-align: right;"></h4></div></div>');
    var $newItem = $('<div class="column last bag_product" style="width: 274px;"><a class="blink"><div class="button column" style="width: 50px;"><img class="home_itemImg" src="" width="50px"/></div></a><a class="blink"> <div class="button column" style="width: 130px;"><h4 class="tight strong home_itemBrand"></h4><p class="tight home_itemName" style="height: 34px;">$50 GIFT CERT</p><p class="tiny nomargin home_itemAux">O/SZ  | </p></div></a><div class="column last" style="width: 68px;"><p class="min-margin tiny lh-small closebtn removeItem button" style="margin-bottom: 10px; text-align: right; font-size:10px;">remove</p><p class="home_itemQty alignright" style="margin: 0;">3</p><h4 class="home_itemPrice HelvBold tiny" style="text-align: right;margin-top: 1px;">$50.00</h4></div></div>');
    //dlog(itemInfo);

    $('.home_itemImg',$newItem).attr('src',itemInfo.IMAGE);//.click(onClickShoppingBagItem);
    
    $('.home_itemName',$newItem).text( itemInfo.NAME );//.parent().click(onClickShoppingBagItem);
    $('.home_itemAux',$newItem).text( itemInfo.SIZE+ ' | ' + itemInfo.COLOR );
    if( $('.home_itemAux',$newItem).text() == ('  | ') ) $('.home_itemAux',$newItem).text('')
    $('.home_itemQty',$newItem).text( itemInfo.QTY );
    $('.home_itemPrice',$newItem).text( itemInfo.PRICE );
    $('.blink',$newItem).attr({href:(itemInfo.NAME != 'Gift Card')?'/product.aspx?id='+itemInfo.PRODUCT_ID:'/giftcards.aspx'});
    $('.removeItem',$newItem).click(onClickRemoveFromShoppingBag);
        //dlog(itemInfo.ITEM_ID);
    $newItem.data('OID',itemInfo.ITEM_ID);
    $newItem.data('PID',itemInfo.PRODUCT_ID);

    $newItem.removeClass('template');
    //$('.closebtn',$newItem).click( onClickRemoveFromShoppingBag );
    return $newItem;
    //dlog($newItem);
    //dlog( $('#mainCartList') );
    
};



//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//ShopBag handlers
function onClickShoppingBagItem(){
    //dlog('ging to take us to this product');
    var $item = $(this).closest('.bag_product');
    var itemOID = $item.data('OID');
    var itemPID = $item.data('PID');
    
    //$.bbq.pushState( 'product='+itemPID+'&sku='+itemOID , 2 ); //merge mode 2 - params argument will completely replace current state
    
}
function onClickRemoveFromShoppingBag(){
    dlog('going to remove from shopping bag');
    dlog( $(this) );
    var $item = $(this).closest('.bag_product');
    var itemOID = $item.data('OID');
    
    $.ajax({ url:'/ajx/_addtocart.aspx', type:'POST', dataType:'json', cache:false, data:{ 'RID':itemOID, 'mode':2, 'QTY':0 } })
        .success( function(data,status){ dlog(data); iface_buildShopBag( data ); })
        .error(function(e){dlog(e);});
    
}



	
