document.write("<script type='text/javascript' src='/shared/bu/jslib/autoEllipsis.js'></script>");
var global_user_id;
var images_path;
function formatToDay(openTime){
    var open_time = new Date(openTime*1000);
    var day = open_time.getDate();
    var month = open_time.getMonth()+1;
    month = month>9?month:"0"+month;
    var year = open_time.getFullYear();
    return month+"/"+day+"/"+year;
}

function getCookie(name) {
    //alert(1);
    var dc = document.cookie;
    //alert(dc);
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0)
        {
            return null;
        }
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }

    return unescape(dc.substring(begin + prefix.length, end));
}

//used for carousel
function getItemHTML(item,layout_label,position)
{
    var itemTitle = item.title ;
    var tempDiv = $('<div id="tempDiv" style="visibility:hidden"></div>');
    $('body').append(tempDiv);
    tempDiv.html(itemTitle).autoEllipsisByWord('',{width:100,lines:3});
    itemTitle = tempDiv.html();
    tempDiv.remove();
    /*itemTitle = (itemTitle && itemTitle.length > 40 ) ? itemTitle.substring(0,40)+"..." : itemTitle ;
    // word break
    itemTitle = wbr(itemTitle, 14);*/
    var args={};
    var carouselStrTmpl = new EJS({
        url: "/shared/bu/js/template/Carousel_Structure.js"
    });
    var _LSIURL = window.location.protocol + '//' + window.location.host;
    args.url = _LSIURL+""+item.thumbnail_url;
    args.auctionId = item.auction_id;
    args.title = item.title;
    args.itemTitle = itemTitle;
    args.number_of_items_per_lot = item.number_of_items_per_lot;
    var current_bid = item.current_bid;
    if(current_bid) 
    {
        current_bid =current_bid.substring(0,(current_bid.indexOf(".") + 3));
    }
    else
    {
        current_bid="0.00";
    }
    
    args.current_bid = current_bid;
    args.auction_type_code = item.auction_type_code;
    args.close_time=item.close_time;
    args.layout_label = layout_label;
    args.position = position;
   	args.currency_symbol = "$";
    if ( typeof(uk_flag) != "undefined" && uk_flag == true ) {
    	args.currency_symbol = "&pound;";
    }
    /*var current_price;
    if(args.auction_type_code == "SLB"){
        current_price = "Sealed Bid";
    }else{
        current_price = args.current_bid;
    }
    var carousel_structure = "<li><div class='imageClass' style='background-image: url("+args.url+");'><a ceid="+args.layout_label+"-image-"+args.position+" href='/auction/view?id="+args.auctionId+"'><img style='border:1px solid #fff;cursor:pointer;' src='/shared/bu/images/imageframe.gif' src="+args.url+" /></a></div><br/><div class='ellipsis'><a  ceid="+args.layout_label+"-text-"+args.position+"  href='/auction/view?id="+args.auctionId+"'>"+args.itemTitle+"</a></div><div style='line-height: 18px;'>Quantity in Lot: "+args.number_of_items_per_lot+"</div><div>Lot Price: "+current_price+"</div>";
    if(args.auction_type_code=="closingsoon"){
        carousel_structure +="<div style='color:#F88B3A'>Closing:"+args.close_time+"</div></li>";
    }else{
        carousel_structure += "</li>";
    }*/
    var carousel_structure = carouselStrTmpl.render(args);
    return carousel_structure;
}

//used for auction view carousel
function getAuctionViewItemHTML(item,index)
{
    var args={};
    var carouselStrTmpl = new EJS({
        url: "/shared/bu/js/template/AuctionView_Carousel_Structure.js"
    });
    args.index=index;
    args.path=images_path;
    args.url = item.tinythumb_url;
    var carousel_structure = carouselStrTmpl.render(args);
    return carousel_structure;
}

//used for auction view lighbox generation
function getAuctionViewLightBoxHTML(item,display,index)
{
    var args={};
    var carouselStrTmpl = new EJS({
        url: "/shared/bu/js/template/AuctionView_LightBox_Structure.js"
    });
    args.largeImageUrl = item.largethumb_url;
    args.widgetImageUrl = item.image_url;
    args.display = display;
    args.path=images_path;
    args.index = index;
    var carousel_structure = carouselStrTmpl.render(args);
    return carousel_structure;
}

function getAuctionViewLightBoxTextHTML(item,display){
    var args={};
    var carouselStrTmpl = new EJS({
        url: "/shared/bu/js/template/AuctionView_LightBoxText_Structure.js"
    });
    args.widgetImageUrl =item.image_url;
    if(display == "block"){
        args.bgUrl = "url('/shared/bu/images/imageEnlargeIcon.gif')";
    }else{
        args.bgUrl = "none";
    }
    args.display = display;
    var carousel_structure = carouselStrTmpl.render(args);
    return carousel_structure;
}

function processClick(e){
    if (!e) {
        e = window.event;
    }
    var theTarget = e.target ? e.target : e.srcElement;
    var pNode = theTarget;
    var pClass = pNode.className;
    pClass = pClass.split(" ")[0];
    if(pClass=="tabNavMiddle"){
        var parentNode = $($(pNode).parent());
        var loggedIn = username ? "loggedIn" : "notLoggedIn";
        var layout = "";
        var layoutEl = document.getElementsByTagName('layout');  //$('layout').each() not working in IE8, so using the traditional way of getting elements.
        for(var i=0;i<layoutEl.length;i++){
            if(layoutData[layoutEl[i].id]){
                layout = layoutData[layoutEl[i].id][loggedIn];
            }else{
                layout = layoutData[loggedIn];
            }
        }
        if (parentNode.hasClass("selected")) {
            return false;
        } else if(layout.collections.carousel.length == 1){
            return false;
        }else {
            $('div.tabContainer div.selected').removeClass("selected");
            parentNode.addClass("selected");
            for(var i=0;i<layout.collections.carousel.length;i++){
                if(parentNode.attr("id") == layout.collections.carousel[i]+"Tabbed"){
                    $("#"+layout.collections.carousel[i]+'TabbedBody').css({
                        'display':'block'
                    });
                    if(carouselObj[layout.collections.carousel[i]+'TabbedCarousel'])
                    {
                        carouselObj[layout.collections.carousel[i]+'TabbedCarousel'].reset();
                    }
                }else{
                    $("#"+layout.collections.carousel[i]+'TabbedBody').css({
                        'display':'none'
                    });
                }
            }
        }

    }
}

$(document).ready(function() {
    $('.inputText').bind("focus",function(){
        if($(this).val() == $(this).attr("title")){
            $(this).val("");
            $(this).css({
                'color':'#333333'
            });
        }
    });
    $('.inputText').bind("blur",function(){
        if($(this).val() == $(this).attr("title") || $(this).val() == ""){
            $(this).val($(this).attr("title"));
            $(this).css({
                'color':'#999999'
            });
        }
    });
    //get data from generic_json.js file
    $.getJSON( "/json/generic_json.js", function(data) {
        d_category = data.category;
        d_locations = data.locations;
        d_item_condition = data.item_condition ;
        d_auction_type = data.auction_type;
        d_shipping_size_classification = data.shipping_size_classification;
        d_shipping_terms = data.shipping_terms;

    
        //fill up category,locations,condition and other drop downs from js file
        var categoryHTML = "";
        var locationsHTML= "";
        var locationsHTMLwoLA = "";
        var conditionsHTML= "";
        var auctionTypeHTML= "";
        var shippingSizeClassHTML= "";
        var shippingTermsHTML= "";
    
        if(typeof d_category != "undefined"){
            for(var i=0;i<d_category.length;i++){
                categoryHTML +='<option value="'+d_category[i].id+'">'+d_category[i].name+'</option>';
            }
            $('div.searchContent').find('select#category1').append(categoryHTML);
            $('div.advancedSearch').find('select#category1').html(categoryHTML);
        }else {
            $.getJSON( "/json/category.js", function(data) {
                d_category = data;
                for(var i=0;i<d_category.length;i++){
                    categoryHTML +='<option value="'+d_category[i].id+'">'+d_category[i].name+'</option>';
                }
                $('div.searchContent').find('select#category1').append(categoryHTML);
                $('div.advancedSearch').find('select#category1').html(categoryHTML);
            });
        }
   
        if(typeof d_locations != "undefined" ){
            for(var i=0;i<d_locations.length;i++){
                locationsHTML +='<option value="'+d_locations[i].id+'">'+d_locations[i].name+'</option>';
            }
            $('div.searchContent').find('select#location').append(locationsHTML);
            $('div.advancedSearch').find('select#location').append(locationsHTML);
        }else {
            $.getJSON( "/json/locations.js", function(data) {
                d_locations = data;
                for(var i=0;i<d_locations.length;i++){
                    locationsHTML +='<option value="'+d_locations[i].id+'">'+d_locations[i].name+'</option>';
                }
                $('div.searchContent').find('select#location').append(locationsHTML);
                $('div.advancedSearch').find('select#location').append(locationsHTML);
            });
        }
    
        if(typeof d_item_condition != "undefined" ){
            for(var i=0;i<d_item_condition.length;i++){
                conditionsHTML +='<option value="'+d_item_condition[i].id+'">'+d_item_condition[i].name+'</option>';
            }
            $('div.searchContent').find('select#item_condition').append(conditionsHTML);
            $('div.advancedSearch').find('select#condition').html(conditionsHTML);
        }else {
            $.getJSON( "/json/item_condition.js", function(data) {
                d_item_condition = data;
                for(var i=0;i<d_item_condition.length;i++){
                    conditionsHTML +='<option value="'+d_item_condition[i].id+'">'+d_item_condition[i].name+'</option>';
                }
                $('div.searchContent').find('select#item_condition').append(conditionsHTML);
                $('div.advancedSearch').find('select#condition').html(conditionsHTML);
            });
        }
    
        if(typeof d_auction_type != "undefined" ){
            for(var i=0;i<d_auction_type.length;i++){
                if(d_auction_type[i].id!="DUT")
                {
                    auctionTypeHTML +='<option value="'+d_auction_type[i].id+'">'+d_auction_type[i].name+'</option>';
                }
            }
            $('div.advancedSearch').find('select#type').html(auctionTypeHTML);
        }else {
            $.getJSON( "/json/auction_type.js", function(data) {
                d_auction_type = data;
                for(var i=0;i<d_auction_type.length;i++){
                    if(d_auction_type[i].id!="DUT")
                    {
                        auctionTypeHTML +='<option value="'+d_auction_type[i].id+'">'+d_auction_type[i].name+'</option>';
                    }
                }
                $('div.advancedSearch').find('select#type').html(auctionTypeHTML);
            });
        }
   
        if(typeof d_shipping_size_classification != "undefined" ){
            for(var i=0;i<d_shipping_size_classification.length;i++){
                shippingSizeClassHTML +='<option value="'+d_shipping_size_classification[i].id+'">'+d_shipping_size_classification[i].name+'</option>';
            }
            $('div.advancedSearch').find('select#size').html(shippingSizeClassHTML);
        }else {
            $.getJSON( "/json/shipping_size_classification.js", function(data) {
                d_shipping_size_classification = data;
                for(var i=0;i<d_shipping_size_classification.length;i++){
                    shippingSizeClassHTML +='<option value="'+d_shipping_size_classification[i].id+'">'+d_shipping_size_classification[i].name+'</option>';
                }
                $('div.advancedSearch').find('select#size').html(shippingSizeClassHTML);
            });
        }
    
        if(typeof d_shipping_terms != "undefined" ){
            for(var i=0;i<d_shipping_terms.length;i++){
                shippingTermsHTML +='<option value="'+d_shipping_terms[i].id+'">'+d_shipping_terms[i].name+'</option>';
            }
            $('div.advancedSearch').find('select#shipping_terms').append(shippingTermsHTML);
            customSelectFunction();
        }else {
            $.getJSON( "/json/shipping_terms.js", function(data) {
                d_shipping_terms = data;
                for(var i=0;i<d_shipping_terms.length;i++){
                    shippingTermsHTML +='<option value="'+d_shipping_terms[i].id+'">'+d_shipping_terms[i].name+'</option>';
                }
                $('div.advancedSearch').find('select#shipping_terms').append(shippingTermsHTML);
                customSelectFunction();
            });
        }
        
    });
});

// Not used.
// $.getJSON( "/json/us_state.js", function(data) {
// for(var i=0;i<d_us_state.length;i++){
//       usStatesHTML +='<option value="'+d_us_state[i].id+'">...'+d_us_state[i].name+'</option>';
//    }
//    $('div.advancedSearch').find('select#location').append(usStatesHTML);*/
// });

// Remove watchlist to be used in auction view & success bid page
function removeWatchlist(el,auction_id){
    $("#watchlistIcon").before("<div class='watchListLoading'>Removing...</div>").remove();
    Invoker.RemoveFromWatchlist(auction_id,{}, function(data,o){
        if(data.error && data.error[0]){
            $(".watchListLoading").before("<div class='itemAddedErrorWatchIcon'>"+data.error[0].error_text+"</div>").remove();
            setTimeout(function(){
                $('.itemAddedErrorWatchIcon').fadeOut("slow",function(){
                    if($(el).attr("pagetype")=="STR"){
                        $('.itemAddedErrorWatchIcon').before("<a pagetype='STR' class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'>Remove Listing</a>").remove();
                    }else{
                        if(str)
                        {
                            $('.itemAddedErrorWatchIcon').before("<a class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'><b>Remove Listing from Watchlist</b></a>").remove();
                        }
                        else
                        {
                            $('.itemAddedErrorWatchIcon').before("<a class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'><b>Remove Auction from Watchlist</b></a>").remove();
                        }
                    }
                });
            },2000);
        }else if(data.result){
            var u_id = getLoggedInUserId();
            if($(el).attr("pagetype")=="STR"){
                $(".watchListLoading").before("<a pagetype='STR' href='#' onclick='return addToWatchList(this,"+u_id+","+auction_id+");'>Add to My Watchlist</a>").remove();
            }else{
                $(".watchListLoading").before("<a class='watchIcon' id='watchlistIcon' href='#' onclick='return addToWatchList(this,"+u_id+","+auction_id+");'><b>Add to My Watchlist</b></a>").remove();
            }
        }
    });
    return false;
}




function addToWatchList(el,user_id,auction_id){
    var params={
        "user_id":user_id,
        "auction_id":auction_id
    };
    $(el).before("<div class='watchListLoading'>Adding...</div>").remove();
    Invoker.addItemToWatchList(params,function(data){
        $('.watchListLoading').before(el).remove();
        if(!data.error){
            //$(el).before("<div class='itemAddedSuccessWatchIcon'>Auction added to <a href='/account/main?tab=WatchList#WatchListAnchor'>Watchlist</a></div>").remove();
            if($(el).attr("pagetype")=="STR"){
                $(el).before("<a pagetype='STR' class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'>Remove Listing</a>").remove();
            }else{
                if(str)
                {
                    $(el).before("<a class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'><b>Remove Listing from Watchlist</b></a>").remove();
                }
                else
                {
                    $(el).before("<a class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'><b>Remove Auction from Watchlist</b></a>").remove();
                }
            }
        }else{
            if(data.error[0].status_code == "403"){
                if($(el).attr("pagetype")=="STR"){
                    $(el).before("<a pagetype='STR' class='notLoggedinErrorIcon' href='javascript:void(0);'>Please Log In</a>").remove();
                }else{
                    $(el).before("<a class='notLoggedinErrorIcon' href='javascript:void(0);'><b>Please Log In to Add to Your Watchlist</b></a>").remove();
                }
                var url=location.pathname+location.search+"&isAddWatchlist=true";
                var element = $('.notLoggedinErrorIcon');
                window.location.href = "/login?page="+escape(url);
            }else if(data.error[0].status_code == "200"){
                if($(el).attr("pagetype")=="STR"){
                    $(el).before("<a pagetype='STR' class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'>Remove Listing</a>").remove();
                }else{
                    if(str)
                    {
                        $(el).before("<a class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'><b>Remove Listing from Watchlist</b></a>").remove();
                    }
                    else
                    {
                        $(el).before("<a class='removeIcon' id='watchlistIcon' href='#' onclick='javascript:return removeWatchlist(this,"+auction_id+");'><b>Remove Auction from Watchlist</b></a>").remove();
                    }
                }
            //$(el).before("<div class='itemAddedErrorWatchIcon'>"+data.error[0].error_text+"</div>").remove();
            }else{
                if($(el).attr("pagetype")=="STR"){
                    $(el).before("<div pagetype='STR' class='itemAddedErrorWatchIcon'>Error!!</div>").remove();
                }else{
                    $(el).before("<div class='itemAddedErrorWatchIcon'>Error, Please try again later</div>").remove();
                }
                setTimeout(function(){
                    $('.itemAddedErrorWatchIcon').fadeOut("slow",function(){
                        $('.itemAddedErrorWatchIcon').before(el).remove();
                    });
                },2000);
            }
        }
    });
    return false;
}

function listingAddtoWatchlist(el,user_id,auction_id,search_query,param){

    var params={
        "user_id":user_id ? user_id : global_user_id,   
        "auction_id":auction_id
    };
    var bgurl = $(el).css("background");
    $(el).css({
        "background":"url('/shared/bu/images/add_watchlist_loading.gif') no-repeat"
    });
    $(el).removeAttr("href");
    Invoker.addItemToWatchList(params,function(data){
        if(!data.error){
            $(el).css({
                "background":"url('/shared/bu/images/saveSearch-success.gif') no-repeat"
            });
            $(el).next().find('label').html("Auction added to Watchlist");
            el.onclick=null;
            $(el).click(function(){
                window.location.href = "/account/main?tab=WatchList#WatchListAnchor";
            });
        }else{
            if(data.error[0].status_code == "403"){
                //  $(el).css({"background":"url('/shared/bu/images/saveSearch-error.gif') -3px 0px no-repeat"});
                if(param) {
                    var url=location.pathname+"?query="+search_query+"&auctionId="+auction_id+"&_page="+param.page+"&sort="+param.sort+"&ascending="+param.ascending+"&isAddWatchlist=true";
                }else{
                    var url = "/";
                }
                window.location.href = "/login?page="+escape(url);
            }else if(data.error[0].status_code == "200"){
                $(el).css({
                    "background":"url('/shared/bu/images/saveSearch-error.gif') 0px 0px no-repeat"
                });
                $(el).next().find('label').html(data.error[0].error_text);
                $(el).next().show();
                el.onclick=null;
                if($(el).next().attr('id')=="watch_tooltip")
                {
                    setTimeout(function(){
                        $(el).next().fadeOut("slow");
                    },2000);
                }
            }else{
                $(el).css({
                    "background":"url('/shared/bu/images/saveSearch-error.gif') 0px 0px no-repeat"
                });
                $(el).next().html(data.error[0].error_text);
                el.onclick=null;
                setTimeout(function(){
                    $(el).fadeOut("slow",function(){
                        $(el).css("background",bgurl);
                        $(el).show();
                        $(el).next().find('label').html("Add to Watchlist");
                      
                        el.onclick=listingAddtoWatchlist(el,global_user_id,auction_id,search_query,param);
                        el.href="/account/main?tab=WatchList&auctionId="+auction_id+"&addSubmit.x=1";
                    });
                },2000);
            }
        }
    });
    return false;

}

function arrayContains(arr,v){
    for (i=0; i<arr.length; i++){
        if (arr[i]==v) {
            return true;
        }
    }
    return false;
}

function shuffle(o){
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

function openWhatsThisPopup(url) {
    window.open (url, "WhatIsThisPopup",
        "width=450," +
        "height=625," +
        "channelmode=0," +
        "directories=0," +
        "location=0," +
        "menubar=0," +
        "resizable=0," +
        "scrollbars=1," +
        "status=0," +
        "titlebar=0," +
        "toolbar=0"
        );
}

function bidAmountValidate(obj,minimum_bid){
    var val = $("input[type='text'][name='bidAmount']").val();
    val = val.replace(/,/,"");
    if(isNaN(val)){
        pushValue(null);
        $("div.bidAmountCheck").show();
        $(obj).prev().focus();
        return false;
    } else  {

	
        if(val<minimum_bid)
        {
            pushValue(null);
            $("div.bidAmountCheck").show();
            $(obj).prev().focus();
            return false;
        }
        else
        {
            pushValue(val);
            $("div.bidAmountCheck").hide();
            return true;
        }
    }
}

function pushValue(v){
    v?$("input[name='bidAmount']").val(v):$("input[name='bidAmount']").val("");
}

function getLoggedInUserId(){
    return getCookie("WWW_SESSION_ID_USER") ? getCookie("WWW_SESSION_ID_USER") : getCookie("WWW_SESSION_ID_DEV_USER");
}

function formatTo12(closeTime){
    var close_time = new Date(closeTime*1000);
    var hours = close_time.getHours();
    var minutes = close_time.getMinutes();
    minutes = minutes + "";
    if (minutes.length == 1){
        minutes = "0" + minutes;
    }
    if(hours>=12){
        if((hours-12)==0){
            return hours+":"+minutes+" PM";
        }else if((hours-12)==12){
            return "12:"+minutes+" AM";
        }else{
            return (hours-12)+":"+minutes+" PM" ;
        }
    }else{
        return hours+":"+minutes+" AM"  ;
    }
}

/* introduce word break \S Match any character NOT whitespace */
function wbr(str, num) { 
    return str.replace(RegExp("(\\S{" + num + "})(\\S)", "g"), function(all,text,char){
        return text + "<wbr>" + char;
    });
}


function states_basedon_country(country_code,state_code){
    if(country_code == "US" || country_code == "CA")
    {
        Invoker.statesBasedOnCountry(country_code,function(msg){
            var insert_text;
            insert_text='<select class="inp-se-Style" name="state" id="dynamic_states" >';
            for(var i=0;i<msg.result.length;i++){
                for(var obj in msg.result[i]){
                    if(obj==state_code)
                    {
                        insert_text+='<option value="'+obj+'"  selected >'+msg.result[i][obj] +'</option>';
                    }
                    else
                    {
                        insert_text+='<option value="'+obj+'" >'+msg.result[i][obj] +'</option>';
                    }
                }
            }
            insert_text+='</select>';
            $('#dynamic_states').after(insert_text).remove();
				
        });
    }//end of CA and US
    else {
        //for non CA and US states
        if(state_code){
            $('#dynamic_states').after('<input class="inp-se-Style" id="dynamic_states" type="text" name="state" value="'+state_code +'"/>').remove();
        } else {
            $('#dynamic_states').after('<input class="inp-se-Style" id="dynamic_states"  type="text" name="state" />').remove();
        }
    }
}




function currentESTTime(t) {
    // create Date object for current location
    d = t?new Date(t):new Date();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    //offset of EST
    var offset = '-4';

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a Date
    return new Date(nd);
}



function viewManifest(user_id,auction_id){
    var id=user_id ? user_id : global_user_id;
    if(id == ""||id == undefined){
        window.location = "/login?page=/";
    }else{
        window.open('/auction/view_csv?id='+auction_id+'','proxy','menubar=yes,width=800,height=600,scrollbars=yes,location=no');
    }
}

