
function check_cart_status2 () {
	if (document.getElementById('yfc_infoDiv')) {
		document.getElementById('yfc_close_btn').innerHTML='<img src=/lib/spytown/close-continue.png>';
	} else
		setTimeout ('check_cart_status2()', 100);
}

function mssAddRegMsg (){
	if  (document.getElementById('custRegDiv_c')){
	var newdiv=document.createElement("div")
	newdiv.setAttribute('id', 'mss-reg-msg');
	var newtext=document.createTextNode("For security purposes , SpyTown does not see, retain, or store any login information of any kind. That includes any usernames, id's or passwords. SpyTown is a proud member of TRUSTe and abides by all their privacy standards.")
	newdiv.appendChild(newtext) //append text to new div
	document.getElementById('custRegDiv').appendChild(newdiv)
	}	else
		setTimeout ('mssAddRegMsg()', 100);
}

//extra things

var shippingStateValue=null;
var shippingZipValue=null;
var shippingCountryValue=null;

var shippingTimeOutId=null;

var globalItems=null;

var shippingMethodScripUrl="https://www.solidcactushosting.com/dev/shipmanager/shippingManager.php?";
var shippingMethodStoreId="spytown";

var J=jQuery;

function hide_standard_methods() {

    if (J("#yfc_shipmethod").length>0) {
        J("#yfc_shipmethod,label:contains('Shipping Method'),#yfc_submitShip").hide();
        J("#yfc_shipmethod").next().remove();
        J("#yfc_submitShip").next().remove();
        J("label:contains('Shipping Method')").next().remove();
    }

	//document.getElementById('yfc_submitShip').style.position = 'absolute';
	//document.getElementById('yfc_submitShip').style.top = '-200px';
	//document.getElementById('yfc_submitShip').style.left = '-200px';

}

function check_cart_status() {

    if (document.getElementById('yfc_infoDiv')) {
		sc_cart_init();
		
		J('#yfc_zipcode').change(zipChangeHandler);
		J('#yfc_state').change(stateChangeHandler);
		J('#yfc_country').change(countryChangeHandler);
	
	    J("#yfc_submitShip").click(function(e){
	        J("#yfc_shipmethod option").each(function(i) {
	            
	            if (this.value==shippingMethod) {
	                J("#yfc_shipmethod option")[0].selectedIndex=i;
	            }
	        
	        });
	        //e.preventDefault();
	    });
	
		//if (document.getElementById('yfc_mymenu-2-label')) {
		//	add_event (document.getElementById('yfc_mymenu-2-label'), 'click', asm_fc_recalc_changes);
		//}

		//asm_fc_process_cart();
	} else
		setTimeout ('check_cart_status()', 100);    

}

function sc_cart_init() {

	initCtrls();

    hide_standard_methods();
    
    J("#yfc_state option").each(function() {
        
            if (this.value.indexOf(" APO")>-1 || this.value.indexOf(" FPO")>-1) {
                this.value=this.value.replace(/ APO/gi,"").replace(/ FPO/gi,"");
            }
        
        });
    
    J("#yfc_zipcode").change(zipChangeHandler);
    J("#yfc_state").change(stateChangeHandler);
    J("#yfc_country").change(countryChangeHandler);
    
    var cart=getItemData();
    
    var itemIds="";
    
    if (cart.items && cart.items.length>0) {
    
        for (var i=0;i<cart.items.length;i++) {
            itemIds=itemIds + cart.items[i].id;
            if (i+1<cart.items.length) 
                itemIds=itemIds + ",";
        }
    
    }
    J.cookie("shippingMethodItems",itemIds,{path:"/",domain:".spytown.com"});
    
    globalItems=itemIds;

    if (J("#yfc_state").val()!="") shippingStateValue=J("#yfc_state").val();
    if (J("#yfc_zipcode").val()!="") shippingZipValue=J("#yfc_zipcode").val();
    if (J("#yfc_country").val()!="") shippingCountryValue=J("#yfc_country").val();
    
    if (shippingStateValue!=null && shippingZipValue!=null && shippingCountryValue!=null) {
        tryLoadData();
    }
}

function toPrice(x) {
    if (x) {
            x = parseFloat(x).toFixed(2).toString();
            var intEnd = x.indexOf('.') - 3;
            for (var i = intEnd, j = 0; i > j; i -= 3) {
                    x = x.substring(0, i) + ',' + x.substring(i, x.length);
            }
            x = x;
    } else {
            x = '0.00';
    }
    currency = "$";
    return currency + x;
}

function getItemData() {

    var cart=new Object();
            
    //items, shipping, tax
    J("#yfc_itemDetails .yui-dt-data tr").each(function(pos) {
   
        if (J(this).hasClass("yui-dt-even") || J(this).hasClass("yui-dt-odd")) {

            if (cart.items==null) 
                cart.items=new Array();
            
            var cartItem=new Object(); 
            
            cartItem.number=cart.items.length;
            cart.items.push(cartItem);
            
            J("td.yui-dt-col-attrs a:first",this).each(function() {
                cartItem.url=this.href;
                
                if (cartItem.url!=null) {
                     if (cartItem.url.substring(0,16)=="javascript:alert") {
                        cartItem.id="hidaynivaoud";
                     } else {
                         cartItem.id=cartItem.url.substring(cartItem.url.lastIndexOf("/")+1).replace(/\.html/gi,"").toLowerCase();
                     }
                     //cartItem.id="36vo16amp3ba";
                }
            });

            if (J("td.yui-dt-col-qty .qty",this).length>0) {
                cartItem.qty=parseInt(J("td.yui-dt-col-qty .qty",this).html());
            }
            if (J("td.yui-dt-col-price .price",this).length>0) {
                cartItem.price=J("td.yui-dt-col-price .price span",this).html();
                cartItem.price=parseFloat(cartItem.price.replace(/[\,\$]/gi,""));                
            }            
        }
    });
    
    return cart;
}

function ensureContainer() {
    
    var container=J("#shippingMethodContainer");
    
    if (container.length==0) {
        J("<div id=\"shippingMethodContainer\" style=\"padding-top:10px;\"></div>").insertAfter(J("#yfc_zipcode"));
        container=J("#shippingMethodContainer");
    }
    return container;
}

function showLoading() {

    var container=ensureContainer();
    
    var loader=J("#shippingMethodLoading");
    
    if (loader.length==0) {
        loader=J("<div id=\"shippingMethodLoading\" style=\"padding-top:10px;\">loading ...</div>").insertAfter(container);
        J("#shippingMethodLoading").next().remove();
    }    
    
    container.css("display","none");
    loader.css("display","block");
}

function hideLoading() {
    J("#shippingMethodContainer").css("display","block");
    J("#shippingMethodLoading").css("display","none");
}

function loadData() {

    showLoading();

    var cart=getItemData();
    
    if (cart==null)
        return;
    
    var url=shippingMethodScripUrl;
    
    if (cart.items) {
        var items="";
        
        shippingMethodItems=(globalItems) ? globalItems : J.cookie("shippingMethodItems");

        if (shippingMethodItems==null)
            shippingMethodItems="";
            
        shippingMethodItems=shippingMethodItems.replace(/\%2C/ig,",");    
        
        shippingMethodItems=shippingMethodItems.split(",");
        
        for (var i=0;i<cart.items.length;i++) {
             items=items + shippingMethodItems[i]+"|"+cart.items[i].qty+"|"+cart.items[i].price;
             if (i+1!=cart.items.length)
                items=items + ",";
        }
        
        url=url + "items=" + items + "&";
        url=url + "country=" + shippingCountryValue + "&";
        url=url + "state=" + (shippingCountryValue.indexOf("US")==0?shippingStateValue:"") +  "&";
        url=url + "zip=" + shippingZipValue + "&";
        url=url + "storeid="+shippingMethodStoreId;
    }

    var old=J("#scShipMethodScriptWorker");
    if (old.length>0) {
         J(old).remove();
    }

    var script = document.createElement('script');
    script.id = 'scShipMethodScriptWorker';
    script.type = 'text/javascript';
    
    script.src = url;
    var heads=document.getElementsByTagName("head");
    if (heads && heads[0]) heads[0].appendChild(script);

    window.shippingTimeOutId=window.setTimeout(function() {
    
        hideLoading();
        
        var container=ensureContainer();
        
        //container.html("Error during loading shipment methods information. Shipping fee will be applied later");
    
    },30000);

}

function renderData(methods) {

    var container=ensureContainer();
   
    window.clearTimeout(window.shippingTimeOutId);
   
    hideLoading();

    container.empty();
    
    if (methods==null)
        methods=new Array();
        
    methods.sort(function(x,y) {
        var a=x[1];
        var b=y[1];

        if (a==null && b==null)
            return 0;
        
        if (a!=null && b!=null) {
    
            if (a < b) {      return -1;   }   
            if (a > b) {      return 1;   }   
            if (a == b) {      return 0;   }
            
        } else {
            if (a!=null)
                return 1;
            else
                return -1;    
        }
    });
    
    for (var i=0;i<methods.length;i++) {
    
        var div=J("<div style=\"text-align:left\"></div>").appendTo(container);
    
        var inp=J("<input style=\"vertical-align:middle;padding-right:5px;\" type=\"radio\" name=\"shipmethod_sc\" />").appendTo(div);

        J(inp).attr("value",methods[i][0]).attr("shippingValue",methods[i][1]).click(function() {
            J.cookie("shippingMethod",this.value,{path:"/",domain:".spytown.com"});
            //update subtotals
            
            var previousShipValue=0;
            var shippingValue=this.getAttribute("shippingValue");
            
            window.shippingMethod=this.value;
            
            updateTotal(parseFloat(shippingValue), previousShipValue);
            
        });
        J(inp).after(document.createTextNode(toPrice(methods[i][1]) + " - " + methods[i][0]));
    }
    /*
    if ($.cookie("shippingMethod")) {
       if (J("input[value=" + $.cookie("shippingMethod") + "]",container).length>0) {	
		
			J("input[value=" + $.cookie("shippingMethod") + "]",container).attr("checked",true);
        
			updateTotal(J("input[value=" + $.cookie("shippingMethod") + "]",container).attr("shippingValue"),0);
        
		}
    }*/
    J("#shipping-state,#shipping-state-for-shipping-calculator").change(stateChangeHandler);
}

function updateTotal(shipV, previousShipValue) {
	if (J("#yfc_taxship_amt").length>0) {
	
	    previousShipValue=parseFloat(J("#yfc_taxship_amt").html().replace(/\,\$/ig,""));
                    
        J("#yfc_taxship_amt").html(toPrice(shipV));
	
	}
	if (J("#yfc_total_amt").length>0) {
	
	    var totalValue=parseFloat(J("#yfc_sub_total").html().replace(/\$/ig,"").replace(/\,/ig,"")) + shipV;
	
        J("#yfc_total_amt").html(toPrice(totalValue));
	
	}
}

function tryLoadData(source) {
    if (shippingZipValue && (shippingStateValue || shippingCountryValue!="US")) {
        loadData();        
    }
}

function stateChangeHandler() {

    shippingStateValue=this.options[this.selectedIndex].value;
    
    J.cookie("shippingState",shippingStateValue,{path:"/",domain:".spytown.com"});
    
    var shipZipCtrl=document.getElementById("yfc_zipcode");
    
    if (shipZipCtrl) {
        if (shipZipCtrl.value=="") {
            this.setAttribute("empty","1");
        } else {
            this.setAttribute("empty","0");
        }
    }
    J("#yfc_state").change(stateChangeHandler);
    J("#yfc_zipcode").change(zipChangeHandler);
    J("#yfc_country").change(countryChangeHandler);
    tryLoadData("state");
}

function zipChangeHandler() {

    J("#yfc_state").change(stateChangeHandler);
    J("#yfc_zipcode").change(zipChangeHandler);
    J("#yfc_country").change(countryChangeHandler);

    shippingZipValue=this.value;
    
    J.cookie("shippingZip",shippingZipValue,{path:"/",domain:".spytown.com"});
    tryLoadData("zip");
}

function countryChangeHandler() {

    shippingZipValue=null;
    shippingStateValue=null;
    
    if (J("#yfc_state").length>0) J("#yfc_state")[0].selectedIndex=0;
    J("#yfc_zipcode").attr("value","");
    
    initCtrls();
    
    J("#yfc_state").change(stateChangeHandler);
    J("#yfc_zipcode").change(zipChangeHandler);
    J("#yfc_country").change(countryChangeHandler);
    
    shippingCountryValue=this.options[this.selectedIndex].value;
    
    //if (shippingCountryValue=="US") J("#yfc_state,label:contains('State')").show(); else J("#yfc_state,label:contains('State')").hide();;
    
    J.cookie("shippingCountry",shippingCountryValue,{path:"/",domain:".spytown.com"});
    
    tryLoadData("country");
}

function initCtrls() {

    shipStateCtrl=document.getElementById("yfc_state");
    if (shipStateCtrl!=null) {
	    if (shipStateCtrl.value=="") {
		    shipStateCtrl.setAttribute("empty","1");
	    } else {
		    shipStateCtrl.setAttribute("empty","0");
	    }
	}
    
    var shipZipCtrl=document.getElementById("yfc_zipcode");
    if (shipZipCtrl) {
		if (shipZipCtrl.value=="") {
			shipZipCtrl.setAttribute("empty","1");
		} else {
			shipZipCtrl.setAttribute("empty","0");
		}
    }
    
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
