function paymentOptionToggle(id){
    var val = document.getElementById(id).value;
    if(val == "C"){
        document.getElementById('paypal_email_display').style.display = 'none';
        document.getElementById('check_name_display').style.display = '';
    }else if(val == "P"){
        document.getElementById('check_name_display').style.display = 'none';
        document.getElementById('paypal_email_display').style.display = '';
    }else if(val == "T"){
        document.getElementById('paypal_email_display').style.display = 'none';
        document.getElementById('check_name_display').style.display = 'none';
    }
}

function loadTConnectRanks(sfiid, eca_catid){
    x_getTConnectStateRank(sfiid, load_state_rank_cb);
    x_getTConnectCountryRank(sfiid, load_country_rank_cb);
    x_getTConnectWorldRank(sfiid, load_world_rank_cb);
    x_getTConnectCityRank(sfiid, load_city_rank_cb);
    if(eca_catid > 0){
        x_getTConnectStateRank(sfiid, 1, load_state_cat_rank_cb);
        x_getTConnectCountryRank(sfiid, 1, load_country_cat_rank_cb);
        x_getTConnectWorldRank(sfiid, 1, load_world_cat_rank_cb);
        x_getTConnectCityRank(sfiid, 1, load_city_cat_rank_cb);

    }
}

function load_city_rank_cb(rank){
    document.getElementById('city_rank').innerHTML = '#'+rank;
    document.getElementById('city_rank_ext').style.display = '';
}

function load_state_rank_cb(rank){
    document.getElementById('state_rank').innerHTML = '#'+rank;
    document.getElementById('state_rank_ext').style.display = '';
}

function load_country_rank_cb(rank){
    document.getElementById('country_rank').innerHTML = '#'+rank;
    document.getElementById('country_rank_ext').style.display = '';
}

function load_world_rank_cb(rank){
    document.getElementById('world_rank').innerHTML = '#'+rank;
    document.getElementById('world_rank_ext').style.display = '';
}

function load_city_cat_rank_cb(rank){
    document.getElementById('city_cat_rank').innerHTML = '#'+rank;
    document.getElementById('city_cat_rank_ext').style.display = '';
}

function load_state_cat_rank_cb(rank){
    document.getElementById('state_cat_rank').innerHTML = '#'+rank;
    document.getElementById('state_cat_rank_ext').style.display = '';
}

function load_country_cat_rank_cb(rank){
    document.getElementById('country_cat_rank').innerHTML = '#'+rank;
    document.getElementById('country_cat_rank_ext').style.display = '';
}

function load_world_cat_rank_cb(rank){
    document.getElementById('world_cat_rank').innerHTML = '#'+rank;
    document.getElementById('world_cat_rank_ext').style.display = '';
}

function switchToFreeShipping(skuid){    
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_switchToFreeShipping(skuid, refreshCb);
        return true;
    }
}

function memberListingWasPickedUp(skuid, sale_date){
    if(skuid > 0 && sale_date.length > 0 && sale_date != 'yyyy-MM-dd'){
        var flag = confirm("Are you sure you wish to mark this member listing as being sold on " + sale_date + "?");
        if(flag){
            progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=UXJ5cmd2YXQuLi4= ', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
            progresswindow.close=function() {
                this.hide();
                x_memberListingWasPickedUp(skuid, sale_date, refreshCb);
                return true;
            }
        }
    }else{
        alert('Invalid item ID or sale date.\nItem ID: ' + skuid + '\nSale date: ' + sale_date);
    }
}



function reactivateMemberListing(skuid){
    if(skuid > 0){
        var flag = confirm("Are you sure you wish to reactivate this member listing and cancel the pending sale?");
        if(flag){
            progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=UXJ5cmd2YXQuLi4= ', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
            progresswindow.close=function() {
                this.hide();
                x_reactivateMemberListing(skuid, refreshCb);
                return true;
            }
        }
    }else{
        alert('Invalid item ID: ' + skuid);
    }
}

function resetDeptSelect(){
    document.getElementById('final_dept').value = '';
    document.getElementById('dept_select').innerHTML = ''; 
    document.getElementById('department').options.length = 0;
    x_getDepartmentsByParentId(-1, -1 , true, -1, buildNewDeptSelect);
}

function buildNewDeptSelectPrePop(catid){
    //clear options
    document.getElementById('department').options.length = 0;
    //build new seleect box with subdepts 
    x_getDepartmentsByParentId(catid,-1 , true, -1, buildNewDeptSelect);
}

function selectDept(catid){
    if(document.getElementById('dept_select').innerHTML != ''){
        document.getElementById('dept_select').innerHTML += ' >> ';
    }
    document.getElementById('dept_select').innerHTML +=  document.getElementById('department').options[document.getElementById('department').options.selectedIndex].text;
    //clear options
    document.getElementById('department').options.length = 0;
    document.getElementById('final_dept').value = catid;
    //build new seleect box with subdepts 
    x_getDepartmentsByParentId(catid,-1 , true, -1, buildNewDeptSelect);
}

function buildNewDeptSelect(arr){
    //add "Select" option
    var objSelect = document.getElementById('department'); 
    var objOption = document.createElement("option");
    objOption.text = 'Select'; 
    objOption.value = "-1";
    if(document.all && !window.opera){
        objSelect.add(objOption);
    }else{
        objSelect.add(objOption, null);
     }
    //add new options from arr
    for(var i in arr){
        var objOption = document.createElement("option");
        objOption.text = arr[i]['category']; 
        objOption.value = arr[i]['id'];
        if(document.all && !window.opera){
            objSelect.add(objOption);
        }else{
            objSelect.add(objOption, null);
         }
    }
}

function updateECACategory(catid){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateECACategory(catid, dummyCb);
        return true;
    }
}

function updateProfileText(text){
    if(text.length > 800){
        alert('Too many characters ('+text.length+' entered). Limit is 800.');
        return true;
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateProfileText(text, dummyCb);
        return true;
    }
}


function updateECACommentStatus(commentid, comment_status){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateECACommentStatus(commentid, comment_status, refreshCb);
        return true;
    }
}

function deleteECAComment(commentid){
    var flag = confirm("Are you sure?");
    if(flag){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=UXJ5cmd2YXQuLi4= ', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            x_deleteECAComment(commentid, refreshCb);
            return true;
        }
    }
}

function deleteECANews(newsid){
    var flag = confirm("Are you sure?");
    if(flag){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=UXJ5cmd2YXQuLi4= ', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            x_deleteECANews(newsid, refreshCb);
            return true;
        }
    }
}

function setWillCall(skuid, shipping_address){
    var option = false;
    if(document.getElementById('will_call_'+skuid).checked){
        option = true;
    }else{
        option = false;
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_setWillCall(skuid, option, shipping_address, setWillCallCb);
        return true;
    }
}

function setWillCallCb(arr){
    document.getElementById('sidebarShipping').innerHTML = arr['shipping'];
    document.getElementById('sidebarTotal').innerHTML = arr['total'];
}

function updateViewInactive(view){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateViewInactive(view, refreshCb);
        return true;
    }
}

function copyToAll(prefix, continent_id, value){
    var type = '';
    if(prefix=='S_'){
        type = 'Standard/Economy';
    }else if(prefix=='2_'){
        type = '2-Day Delivery';
    }else if(prefix=='1_'){
        type = '1-Day Delivery';
    }
    var choice = confirm('Are you SURE you want to make $'+value+' the '+type+' Shipping & Handling fee for every country in this continent that does not currently have an amount?');
    if(choice){
        x_copyToAll(prefix, continent_id, value, copyToAll_cb);
    }
}

function copyToAll_cb(arr){
    var val = arr[0];
    var len = arr[1];
    for(var i=2;i<len;i++){
        if(document.getElementById(arr[i]).value==''){
            document.getElementById(arr[i]).value=val;
        }
    }
}

function deleteAllPreviewItems(){
    var flag = confirm("Are you sure?");
    if(flag){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=UXJ5cmd2YXQuLi4= ', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            x_deleteAllPreviewItems(deleteAllPreviewItems_cb);
            return true;
        }
    }
}


function flipPayments(id){
    if (id.checked) {
        var form = document.checkout_form;
        for(i=0; i<form.elements.length; i++){
            var element = form.elements[i];
            if (element.type == "radio" && element.name == 'paytype') {
                if (element.value != 'C' && element.value.substring(0,2) != 'C-') {
                    element.checked=false;
                    element.disabled=true;
                }
                if (element.value == 'C') {
                    element.checked=true;
                }
            }
        }

    } else {
        var form = document.checkout_form;
        for(i=0; i<form.elements.length; i++){
            var element = form.elements[i];
            if (element.type == "radio" && element.name == 'paytype') {
                element.checked=false;
                element.disabled=false;
                if (element.value == 'C') {
                    element.checked=true;
                }
            }
        }
    }
}

function deleteAllPreviewItems_cb(){
    window.location.href = '/ECA/ECAMultiLister.php';
}

function deleteMultiListerPreviewItem(id){
    var flag = confirm("Are you sure?");
    if(flag){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=UXJ5cmd2YXQuLi4= ', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            x_deleteMultiListerPreviewItem(id, refreshCb);
            return true;
        }
    }
}

function saveMultiListerPreviewItem(id){
    var theForm = document.getElementById('form_'+id);
    var e = theForm.elements;
    var str = "";
    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        fvalue = fvalue.replace("$", "");
        if(fvalue != ''){
            str += fname + "=" + encodeURI(fvalue) + "&";
        }
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=Rm5pdmF0Li4u', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_saveMultiListerPreviewItem(str, refreshCb);
        return true;
    }
}

function setMultiListerAddresses(){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=Rm5pdmF0Li4u', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_setMultiListerAddresses(document.getElementById('shipfrom_address_id').value, document.getElementById('pickup_address_id').value, doNothing);
        return true;
    }
}

function updateECAOrderDetail(ordid, skuid, shipping_type, tracking_number){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateECAOrderDetail(ordid, skuid, shipping_type, tracking_number, updateECAOrderDetail_cb);
        return true;
    }
}

function updateECAOrderDetail_cb(ret_val){
    if(ret_val == 1){
        //no tracking number entered
        alert('You must enter a tracking number and carrier. For digital products, or those with no tracking numbers available, \"None\" is a valid entry.');
    }else{
        window.location.href = window.location.href;
    }
}

function updateECAPaymentMethod(method, checkname, paypal_email){
    if(method == 'P' && paypal_email == ''){
        alert('You must enter a PayPal email address to use the PayPal option.');
        return true;
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateECAPaymentMethod(method, checkname, paypal_email, updateECAPaymentMethod_cb);
        return true;
    }
}

function updateECAPaymentMethod_cb(result){
    if(result == 2){
        alert('You entered an invalid PayPal email address. Your payment information was NOT saved!');
    }
}

function updateECAAboutUs(about_us){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateECAAboutUs(about_us, doNothing);
        return true;
    }
}

function updateECAReturnsPolicy(policy){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateECAReturnsPolicy(policy, doNothing);
        return true;
    }
}

function deletePendingItem(id){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_deletePendingItem(id, deletePendingItemCb);
        return true;
    }
}

function deletePendingItemCb(id){
    document.getElementById(id).style.display = 'none';
}

function updateItemListerCurrency(currency_id){
    x_updateItemListerCurrency(currency_id, updateItemListerCurrencyCb);
}

function updateItemListerCurrencyCb(currency_symbol){
    document.getElementById('currency1').innerHTML = currency_symbol;
    document.getElementById('currency2').innerHTML = currency_symbol;
    document.getElementById('currency3').innerHTML = currency_symbol;
}

function setECACurrency(sfiid){
    var currency_id = document.getElementById('currency').options[document.getElementById('currency').selectedIndex].value;
    if(sfiid > 0 && currency_id > 0){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            x_setECACurrency(currency_id, sfiid, doNothing);
            return true;
        }
    }
}

function updateDOD_2(action) {
    
   if(document.getElementById("radioyes").checked){
       var e = document.getElementById("dealOfDayForm").depts;
        var list = "";
        for (var i = 0; i < e.length; i++) {
            if(e[i].checked == true){
                list += e[i].value + ",";
            }
        }
        list = list.slice(0, list.length-1);
        x_updateDealOfDay(list, dummyCb);
   }else{
       x_deleteDealOfDay(dummyCb);
   }
     progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
     progresswindow.close=function() {
        this.hide();
        window.location.href='/member_benefits5.php';
    }
}



function saveECAShippingFeesForContinent(continent, skuid) {
    var theForm = document.getElementById('form_'+continent);
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=',  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        fvalue = fvalue.replace("$", "");
        if(fvalue != '' && isNumeric(fvalue)){
            str += fname + "=" + encodeURI(fvalue) + "&";
        }
    }
    
    x_saveECAShippingFeesForContinent(str, continent, skuid, saveECAShippingFeesCb);
    return true;
}

function saveECAShippingFeesCb(results){
    document.getElementById('total_countries').innerHTML = results['total_country_count'];
    document.getElementById(results['continent']+'_total').innerHTML = results['continent_count'];
    window.location.href = window.location.href;
}

function toggleDisplay(id){
    var item = document.getElementById(id);
    if(item.style.display == ''){
        item.style.display = 'none';
    }else{
        item.style.display = '';
    }
}

function updateECAPasswordInfo(action) {
    if(document.getElementById('password').value==document.getElementById('password_confirm').value){
    var theForm = document.getElementById('ECAPasswordInfoForm');
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=',  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
    
    x_updateECAPasswordInfo(str,refreshCb);
    return true;
    }else{
        alert('Passwords do not match!');
    }
}

function updateECANotifyInfo(action) {
    var theForm = document.getElementById('ECANotifyInfoForm');
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=',  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
    
    x_updateECANotifyInfo(str,refreshCb);
    return true;
}

function updateECAOptionalNotices(action) {
    var theForm = document.getElementById('ECAOptionalNoticesForm');
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=',  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue = 'N';
        if(e[i].checked){
            fvalue = 'Y';
        }
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
    
    x_updateECAOptionalNotices(str,refreshCb);
    return true;
}
function updateECAContactInfo(action) {
    var theForm = document.getElementById('ECAContactInfoForm');
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=',  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
    
    x_updateECAContactInfo(str,refreshCb);
    return true;
}

function updateECAPublicInfo(action) {
    var theForm = document.getElementById('ECAPublicInfoForm');
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=',  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
    
    x_updateECAPublicInfo(str, refreshCb);
    return true;
}

function setItemFeatured(id, featured){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_setItemFeatured(id, featured, doNothing);
        return true;
    }
}

function setItemActive(id, active){
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act=SGNxbmd2YXQuLi4=', 'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_setItemActive(id, active, doNothing);
        return true;
    }
}

function doNothing(){
}

function builddropdown(){
    var filter = document.getElementById("filter").options[document.getElementById("filter").options.selectedIndex].value;
    var ddl = document.getElementById("filtertype")
    ddl.options.length = 0;
    var equals = document.createElement("option");
    equals.value = "=";
    equals.appendChild(document.createTextNode("="));
    var gt = document.createElement("option");
    gt.value = ">";
    gt.appendChild(document.createTextNode(">"));
    var lt = document.createElement("option");
    lt.value = "<";
    lt.appendChild(document.createTextNode("<"));
    var contains = document.createElement("option");
    contains.value = " like \'%~FILTERVALUE~%\'";
    contains.appendChild(document.createTextNode("contains"));
    var is = document.createElement("option");
    is.value = "=\'~FILTERVALUE~\'";
    is.appendChild(document.createTextNode("is"));
    var gtv = document.createElement("option");
    gtv.value = ">\'~FILTERVALUE~\'";
    gtv.appendChild(document.createTextNode(">"));
    var ltv = document.createElement("option");
    ltv.value = "<\'~FILTERVALUE~\'";
    ltv.appendChild(document.createTextNode("<"));
    
    if(filter=="a.id" || filter=="a.weight" || filter=="b.sfi_price" || filter=="b.cost"){
        ddl.appendChild(equals);
        ddl.appendChild(gt);
        ddl.appendChild(lt);
    }

    if(filter=="a.sku" || filter=="a.name" || filter=="a.description"){
        ddl.appendChild(is);
        ddl.appendChild(contains);
    }

    if(filter=="a.modify_date"){
        ddl.appendChild(is);
        ddl.appendChild(gtv);
        ddl.appendChild(ltv);
    }
}

function convertWeight(orig_weight){
    var weight = 0;
    var weight_unit = document.getElementById('weight_unit').options[document.getElementById('weight_unit').options.selectedIndex].value;
    if(weight_unit == 'P'){
        document.getElementById('weight').innerHTML = orig_weight.toFixed(2);
    }else if(weight_unit == 'O'){
        weight = orig_weight*16;
        document.getElementById('weight').innerHTML = weight.toFixed(2);
    }else{
        weight = orig_weight/2.2;
        document.getElementById('weight').innerHTML = weight.toFixed(2);
    }
}

function toggleCountryAlert(address_id){
    x_getAddressById(address_id,toggleCountryAlertCb);
}

function toggleCountryAlertCb(address){
    var fulltext = address['country_full'];
    var country = address['country'];
    if(country == 'US'){
        document.getElementById('ship_cost_text').style.display = '';
        var ddl = document.getElementById("shipping_option")
        ddl.options.length = 0;
        var equals = document.createElement("option");
        equals.value = "Y";
        equals.appendChild(document.createTextNode("Yes. I will enter my own shipping fees below."));
        ddl.appendChild(equals);
        var gt = document.createElement("option");
        gt.value = "C";
        gt.appendChild(document.createTextNode("Yes. I would like TripleClicks to automatically calculate shipping fees for this product."));
        ddl.appendChild(gt);
        /*var lt = document.createElement("option");
        lt.value = "C";
        lt.appendChild(document.createTextNode("No. This product is only available for local pickup."));
        ddl.appendChild(lt);*/
    }else{
        document.getElementById('ship_cost_text').style.display = 'none';
        var ddl = document.getElementById("shipping_option")
        ddl.options.length = 0;
        var equals = document.createElement("option");
        equals.value = "Y";
        equals.appendChild(document.createTextNode("Yes. I will enter my own shipping fees below."));
        ddl.appendChild(equals);
        /*var lt = document.createElement("option");
        lt.value = "C";
        lt.appendChild(document.createTextNode("No. This product is only available for local pickup."));
        ddl.appendChild(lt);*/
    }
    document.getElementById('country_text').innerHTML = fulltext;
}

function updatePriceBox(){
    var retail_price = document.getElementById('sfi_price').value;
    var whole_price = document.getElementById('whole_price').value;
    if(retail_price > 0 && whole_price > 0){
        var margin = (whole_price/100)*retail_price;
        var profit = retail_price-margin;
        document.getElementById('margin').innerHTML = margin.toFixed(2);
        document.getElementById('profit').innerHTML = profit.toFixed(2);
        document.getElementById('retail_price_box').innerHTML = ((retail_price*100)/100).toFixed(2);
        document.getElementById('whole_price_box').innerHTML = whole_price;
        document.getElementById('pricebox').style.display = '';
    }else{
        document.getElementById('pricebox').style.display = 'none';
    }
    
}

function toggleCardEditLink(id1, id2, value){
    if(isNumeric(value)){
        document.getElementById(id1).style.display = '';
        document.getElementById(id2).style.display = 'none';
    }else{
        document.getElementById(id1).style.display = 'none';
        document.getElementById(id2).style.display = '';
    }
}

function toggleVisibility(id){
    if(document.getElementById(id).style.display != 'none'){
        document.getElementById(id).style.display = 'none';
    }else{
        document.getElementById(id).style.display = '';
    }
}

function deleteImage(id, sequence){
    x_deleteImage(id, sequence, refresh_cb);
}

function checkAgree() {
    if (!document.getElementById('agree').checked){ 
        alert('You must agree to the terms and conditions before placing this order!'); 
        return false; 
    }
    return true;
}

function addPaymentRequest(action) {
    var flag = confirm("Are you sure?");
    if(flag){
        var paypalemail = document.getElementById("paypalemail").value;
        var method = "";
        var radioButtons = document.getElementsByName("radio");
            for (var x = 0; x < radioButtons.length; x ++) {
                if (radioButtons[x].checked) {
                    method = radioButtons[x].value;
                }
              }
        if(method != "") {
            progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
            progresswindow.close=function() {
                this.hide();
                x_addPaymentRequest(method, paypalemail, dummyCb);
                window.location.href=window.location.href;
                return true;
            }
        }else{
            alert("Invalid Selection");
        }
    }
}

function addTrackingInfo(id){
    var result = confirm('Are you sure? Please double check all shipping information for accuracy. Once submitted, this information can not be edited.');
    if(result){
        var carrier = document.getElementById("carrier" + id).value;
        var tracking_number = document.getElementById("tracking_number" + id).value;
        var shipday = document.getElementById("shipday" + id).value;
        var shipmo = document.getElementById("shipmo" + id).value;
        var shipyr = document.getElementById("shipyr" + id).value;
        var shipdate = shipyr + "-" + shipmo + "-" + shipday;
        var flag = true;
        if(carrier == '' || carrier == 'Select'){
            alert('Please select a carrier');
            flag = false;
        }
        if(!isNumeric(shipday) || !isNumeric(shipmo) || !isNumeric(shipyr)){
            alert('Invalid shipping date. All date fields must be numeric.');
            flag = false;
        }
        if(shipday < 1 || shipday > 31 || shipmo < 1 || shipmo > 12 || shipyr < 2009){
            alert('Invalid shipping date.');
            flag = false;
        }
        if(tracking_number == ''){
            alert('Please enter a tracking number.');
            flag = false;
        }
        if(flag){
            x_addTrackingInfo(id, carrier, tracking_number, shipdate, tracking_cb);
        }
    }
}

function tracking_cb(result){
    if(result == 0){
        alert('An error has occurred. The shipping details were not saved, and the buyer was not notified. Please try again or contact Customer Service: support@tripleclicks.com');
    }else{
        var str = '';
        str += "<p>We have just sent the buyer an e-mail notification confirming the shipment date, tracking number, etc. that you provided.</p>";
        str += "<p>As soon as delivery is confirmed, sale earnings will be released to your Private Seller account. You will receive an e-mail notifying you of this.</p>";
        str += "<p>P.S. Have other items you want to sell on TripleClicks. Submit them <a href='/myaccount/itemLister.php'>HERE</a>.</p>";
        document.getElementById("displaydiv" + result).innerHTML = str;
    }
}

function deleteCard(id){
    var result = confirm('Are you sure?');
    if(result){
        x_deleteCard(id, refresh_cb);
    }
}

function updateCheckoutSidebar() {
    x_getCartMethod("getSize",sidebarSizeCb);
    x_getCartMethod("getSvp",sidebarSvpCb);
    x_getCartMethod("getSubtotal",sidebarSubtotalCb);
    x_getCartMethod("getShipping",sidebarShippingCb);
    if (document.getElementById('billing_country').options[document.getElementById('billing_country').selectedIndex].value == 'US' && document.getElementById('billing_state').options[document.getElementById('billing_state').selectedIndex].value == 'NE') {
        x_getCartMethod("doTax",sidebarTaxCb);
    } else {
        x_getCartMethod("setTax",0,sidebarTaxCb);
    }
    x_getCartMethod("getTax",sidebarTaxCb);
    x_getCartMethod("getTotal",sidebarTotalCb);
    return true;
}

function sidebarSizeCb(result) {
    document.getElementById("sidebarSize").innerHTML=parseFloat(result).toFixed(0);
}
function sidebarSvpCb(result) {
    document.getElementById("sidebarSvp").innerHTML=parseFloat(result).toFixed(1);
}
function sidebarSubtotalCb(result) {
    document.getElementById("sidebarSubtotal").innerHTML=parseFloat(result).toFixed(2);
}
function sidebarShippingCb(result) {
    document.getElementById("sidebarShipping").innerHTML=parseFloat(result).toFixed(2);
}
function sidebarTaxCb(result) {
    document.getElementById("sidebarTax").innerHTML=parseFloat(result).toFixed(2);
}
function sidebarTotalCb(result) {
    document.getElementById("sidebarTotal").innerHTML=parseFloat(result).toFixed(2);
}

function OpenWin(Loc, Width, Height) {
    var WinInfo =
    "toolbar=yes,scrollbars=yes,directories=no,resizable=yes,menubar=yes,width=" +
    Width + ",height=" + Height
    wPageWindow = window.open(Loc, "wImageWindow", WinInfo);
    wPageWindow.focus();
}

function validateCreditCard(){
    var paytype = "";
    for (i=0;i<document.checkoutform.paytype.length;i++) {
        if (document.checkoutform.paytype[i].checked) {
            paytype = document.checkoutform.paytype[i].value;
        }
    }
    
    if(paytype == "C"){
        var expyr = document.getElementById('ccexpyr').options[document.getElementById('ccexpyr').selectedIndex].value;
        var expmo = document.getElementById('ccexpmo').options[document.getElementById('ccexpmo').selectedIndex].value;
        var now = new Date();
        if(document.getElementById('ccnum').value == ""){
            alert('Credit card number is required.');
        }else if(expyr < now.getFullYear()){
            alert('Card expired.');
        }else if(expyr == now.getFullYear() && expmo < (now.getMonth() + 1)){
            alert('Card expired.');
        }else if(document.getElementById('ccname').value == ""){
            alert('Cardholder name required.');
        }
    }
}

function validateAddress(type){
    if(document.getElementById(type + 'first').value == ""){
        alert ('First name is required.');
    }else if(document.getElementById(type + 'last').value == ""){
        alert ('Last name is required.');
    }else if(document.getElementById(type + 'address').value == ""){
        alert ('Address is required.');
    }else if(document.getElementById(type + 'city').value == ""){
        alert ('City is required.');
    }else if(document.getElementById(type + 'country').options[document.getElementById(type + 'country').selectedIndex].value == 'US' && (document.getElementById(type + 'state').options[document.getElementById(type + 'state').selectedIndex].value == "--")){
        alert('State is required.');
    }else if(document.getElementById(type + 'zip').value == "" && document.getElementById(type + 'country').options[document.getElementById(type + 'country').selectedIndex].value == 'US') {
        alert ('Zip is required.');
    }else if(document.getElementById(type + 'zip').value == "" && document.getElementById(type + 'country').options[document.getElementById(type + 'country').selectedIndex].value == 'PR') {
        alert ('Zip is required.');
    }else if(document.getElementById(type + 'zip').value == ""){
        alert ('Zip is required.');
    }else if(document.getElementById(type + 'country').options[document.getElementById(type + 'country').selectedIndex].value == "--"){
        alert('Country is required.');
    }else if(document.getElementById(type + 'email').value == ""){
        alert ('Email is required.');
    }else if (document.getElementById(type + 'phone').value == "" && document.getElementById(type + 'country').options[document.getElementById(type + 'country').selectedIndex].value != 'US'){
        alert ('A phone number is required for customs for addresses outside of the US.');
    } else {
        updateCheckoutAddress(type);
        return true;
    }
    return false;
}

function updateCheckoutAddress(type){
    if (type == 'billing_' && document.getElementById(type + 'country').options[document.getElementById(type + 'country').selectedIndex].value == 'US' && document.getElementById(type + 'state').options[document.getElementById(type + 'state').selectedIndex].value == 'NE') {
        x_getCartMethod("doTax",sidebarTaxCb);
    }else if (type == 'billing_'){
        x_getCartMethod("setTax",0.00,sidebarTaxCb);
    } else if (type=='shipping_') {
        doShipping();
        x_getCartMethod("getShipping",sidebarShippingCb);
    }
    var str = "";
    str += document.getElementById(type + 'first').value + ' ';
    str += document.getElementById(type + 'last').value + '<br>';
    str += document.getElementById(type + 'address').value + '<br>';
    str += document.getElementById(type + 'city').value + ', ';
    str += document.getElementById(type + 'state').options[document.getElementById(type + 'state').selectedIndex].value + '  ';
    str += document.getElementById(type + 'zip').value + '<br>';
    str += document.getElementById(type + 'country').options[document.getElementById(type + 'country').selectedIndex].value + '<br>';
    str += document.getElementById(type + 'phone').value + '<br>';
    str += document.getElementById(type + 'email').value;
    document.getElementById(type + 'display').innerHTML = str;
    updateCheckoutSidebar();
}

function doShipping() {
    var shiptype = document.getElementById('shiptype').options[document.getElementById('shiptype').selectedIndex].value;
    str = "";
    str += "firstname=" + encodeURI(document.getElementById('shipping_first').value) + "&";
    str += "lastname=" + encodeURI(document.getElementById('shipping_last').value) + "&";
    str += "address=" + encodeURI(document.getElementById('shipping_address').value) + "&";
    str += "city=" + encodeURI(document.getElementById('shipping_city').value) + "&";
    str += "state=" + document.getElementById('shipping_state').options[document.getElementById('shipping_state').options.selectedIndex].value + "&";
    str += "country=" + document.getElementById('shipping_country').options[document.getElementById('shipping_country').options.selectedIndex].value + "&";
    str += "zip=" + encodeURI(document.getElementById('shipping_zip').value) + "&";
    x_doShipping(str,shiptype,shippingCb);
    updateCheckoutSidebar();
}

function shippingCb(result) {
    if (result*1==result && result >= 0) {
        //Set Shipping
        x_getCartMethod("getShipping",sidebarShippingCb);
    } else {
        //Probably had an error, display it
        alert(result);
    }
}

function copyAddress(){
     document.getElementById('shipping_first').value = document.getElementById('billing_first').value;
    document.getElementById('shipping_last').value = document.getElementById('billing_last').value;
    document.getElementById('shipping_address').value = document.getElementById('billing_address').value;
    document.getElementById('shipping_city').value = document.getElementById('billing_city').value;
    var state_max = document.getElementById('shipping_state').options.length;
    for(var count=0;count<state_max;count++){
        if(document.getElementById('shipping_state').options[count].value == document.getElementById('billing_state').options[document.getElementById('billing_state').options.selectedIndex].value){
            document.getElementById("shipping_state").options[count].selected = true;
        }
    }
    var country_max = document.getElementById('shipping_country').options.length;
    for(var count=0;count<country_max;count++){
        if(document.getElementById('shipping_country').options[count].value == document.getElementById('billing_country').options[document.getElementById('billing_country').options.selectedIndex].value){
            document.getElementById("shipping_country").options[count].selected = true;
        }
    }
    document.getElementById('shipping_zip').value = document.getElementById('billing_zip').value;
    document.getElementById('shipping_phone').value = document.getElementById('billing_phone').value;
    document.getElementById('shipping_email').value = document.getElementById('billing_email').value;   
}

function setCheckoutAddress(type) {
    e = document.getElementById(type);
    id = e.options[e.selectedIndex].value;
    if (type == 'shipping_prevaddress') {
        x_getAddressById(id,setCheckoutShippingAddressCb);
    } else if (type=='billing_prevaddress'){
        x_getAddressById(id,setCheckoutBillingAddressCb);
    }
    return true;
}

function setCheckoutShippingAddressCb(address){
    document.getElementById('shipping_first').value = address['firstname'];
    document.getElementById('shipping_last').value = address['lastname'];
    document.getElementById('shipping_address').value = address['address'];
    document.getElementById('shipping_city').value = address['city'];
    var state_max = document.getElementById('shipping_state').options.length;
    for(var count=0;count<state_max;count++){
        if(document.getElementById('shipping_state').options[count].value == address['state']){
            document.getElementById("shipping_state").options[count].selected = true;
        }
    }
    var country_max = document.getElementById('shipping_country').options.length;
    for(var count=0;count<country_max;count++){
        if(document.getElementById('shipping_country').options[count].value == address['country']){
            document.getElementById("shipping_country").options[count].selected = true;
        }
    }
    document.getElementById('shipping_zip').value = address['zip'];
    document.getElementById('shipping_phone').value = address['phone'];
    document.getElementById('shipping_email').value = address['email'];
}

function setCheckoutBillingAddressCb(address){
    document.getElementById('billing_first').value = address['firstname'];
    document.getElementById('billing_last').value = address['lastname'];
    document.getElementById('billing_address').value = address['address'];
    document.getElementById('billing_city').value = address['city'];
    var state_max = document.getElementById('billing_state').options.length;
    for(var count=0;count<state_max;count++){
        if(document.getElementById('billing_state').options[count].value == address['state']){
            document.getElementById("billing_state").options[count].selected = true;
        }
    }
    var country_max = document.getElementById('billing_country').options.length;
    for(var count=0;count<country_max;count++){
        if(document.getElementById('billing_country').options[count].value == address['country']){
            document.getElementById("billing_country").options[count].selected = true;
        }
    }
    document.getElementById('billing_zip').value = address['zip'];
    document.getElementById('billing_phone').value = address['phone'];
    document.getElementById('billing_email').value = address['email'];
}

function cancelSO(){
    var blah = confirm("Are you sure?");
    if(blah){
        x_cancel_SO(refresh_cb);
    }
}

function activateSO(){
    var blah = confirm("Are you sure?");
    if(blah){
        x_activateSO(soindex_cb);
    }
}

function soindex_cb(result){
    if(result==1){
        alert('You must enter your billing and shipping information before your Standing Order can be activated');
        document.location.href = "http://www.tripleclicks.com/myaccount/SOInfo.php";
    }else{
        document.location.href = "http://www.tripleclicks.com/myaccount/StandingOrder.php";
    }
}

function deleteSO(){
    x_deleteSO(refresh_cb);
}

function refresh_cb(){
    document.location.href = document.location.href;
}

function setSpecialFunding(action, type){
 progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }
    var foo = 'N';
    if(document.getElementById(type).checked == true){
        foo = 'Y';
    }
    x_setSpecialFunding(foo, type, dummyCb);
}

function removeSOItem(id){
    x_removeSOItem(id, addSOItem_cb);
}

function updateSOQty(count, id){
    var qty = document.getElementById('qty'+count).value;
    x_updateSOQty(id, qty, addSOItem_cb);
}

function addSOItem(){
    var id = document.getElementById('additemid').value;
    var qty = document.getElementById('additemqty').value;
    x_addSOItem(id, qty, addSOItem_cb);
}

function addSOItem_cb(result){
    if(result != "success"){
        alert(result);
    }
    document.location.href = document.location.href;
}

function addCard(action){
    var expmo = document.getElementById('expmo').options[document.getElementById('expmo').selectedIndex].value;
    var expyr = document.getElementById('expyr').options[document.getElementById('expyr').selectedIndex].value;
    var cctype = document.getElementById('cctype').options[document.getElementById('cctype').selectedIndex].value;
    var ccname = document.getElementById('ccname').value;
    var ccnum = document.getElementById('ccnum').value;
    var cvv2 = 0;
    //document.getElementById('cvv2').value;
    x_addCard(cctype,ccnum,cvv2,expmo,expyr,ccname,addCard_cb);
}

function addCard_cb(result){
    if(result != "success"){
        alert(result);
    }
        document.location.href = document.location.href;
}

function setPaymentType(action, paytype){
    var type = '';
    var string = '';
    if(paytype == "Y"){
        string = "primpaytype";
    }else{
        string = "secpaytype";
    }
    var radioButtons = document.getElementsByName(string);
    for (var x = 0; x < radioButtons.length; x ++) {
        if (radioButtons[x].checked) {
            type = radioButtons[x].value;
        }
    }
    x_setPaymentType(type,paytype,payment_cb);
}

function payment_cb(msg){
    if(msg != ""){
        alert(msg);
    }
    document.location.href = document.location.href;
}

function updateLocalPickup(sequence, action){
    var local_pickup;
    if(document.getElementById("local_pickup_" + sequence).checked){
        local_pickup = "Y";
    }else{
        local_pickup = "N";
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        x_updateLocalPickup(sequence, local_pickup, update_local_pickup_cb);
        return true;
    }
}

function update_local_pickup_cb(result){
    if(result[1] > 0){
        alert(result[0]);
        document.getElementById('local_pickup_' + result[1]).checked = false;
    }
}

function updateBarter(sequence, action){
    var barter;
    if(document.getElementById("barter" + sequence).checked){
        barter = "Y";
    }else{
        barter = "N";
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }
    x_updateBarter(sequence, barter, dummyCb);
}

function updateObo(sequence, action){
    var obo;
    if(document.getElementById("obo" + sequence).checked){
        obo = "Y";
    }else{
        obo = "N";
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }
    x_updateObo(sequence, obo, dummyCb);
}

function deleteItem(sequence, action){
    var bool = confirm('Are you sure?');
    if(bool){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            x_deleteItem(sequence, refreshCb);
            return true;
        }
    }
}

function refreshCb(){
    window.location.href = window.location.href;
}

function updateItemPrice(sequence, action){

    if(document.getElementById("price" + sequence).value.length <= 0){
        alert('You must enter a price.');
    }else if(!isNumeric(document.getElementById("price" + sequence).value)){
        alert('You must enter a valid number.');
    }else{
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            return true;
        }

        x_updateItemPrice(sequence, document.getElementById("price"+sequence).value, dummyCb);
    }

}

function isNumeric(sText){
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++){ 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1){ 
            IsNumber = false;
        }
    }
    return IsNumber;

}

function displayProgress(action,title,dispAlert) {
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action, title, 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        if (dispAlert) {
            alert(title);
        }
        return true;
    }
    return true;
}

function suggestDepartment(action, department) {
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }
    x_suggestDepartment(department,suggestCb);
    return true;
}

function suggestCb(result){
        document.getElementById("suggest").innerHTML = result;
}

function stopMemberPhotoUpload(result, image_name, width){
    //0 = success
    //1 = upload error
    //2 = file size too large
    //3 = invalid image type
    //4 = image not tied to item ID
    //5 = invalid sequence
    //6 = SQL error
   document.getElementById("error").innerHTML = "";
   if(result == 0){
       document.getElementById("image1").innerHTML = "<img src=\"/images/memberPhotos/" + image_name + "?asdf=" + Math.random()+ "\" width=\"" + width  +  "\">";
   }else if(result == 1){
       document.getElementById("image1").innerHTML = "An error occurred while uploading your file. Please try again later.";
   }else if(result == 2){
       document.getElementById("image1").innerHTML = "File size too large. Images must be no larger than 1 Megabyte in size";
   }else if(result == 3){
       document.getElementById("image1").innerHTML = "Invalid file type. Only JPG, GIF, and PNG files are allowed";
   }else if(result == 4){
       document.getElementById("image1").innerHTML = "Invalid item ID specified for image";
   }else if(result == 6){
       document.getElementById("image1").innerHTML = "An SQL error has occurred. Your image has been saved to the filesystem, but the caption was not saved.";
   }else if(result == 7){
       document.getElementById("image1").innerHTML = "You do not have permission to modify this item.";
   }
}

function stopUpload(result, image_name, sequence){
    //0 = success
    //1 = upload error
    //2 = file size too large
    //3 = invalid image type
    //4 = image not tied to item ID
    //5 = invalid sequence
    //6 = SQL error
    if(sequence > 0 && sequence < 4 && result != 5){
        document.getElementById("error").innerHTML = "";
       if(result == 0){
           document.getElementById("image" + sequence).innerHTML = "<img src=\"/tpImages/members/resized/" + image_name + "\" width=\"320\">";
           document.getElementById("update" + sequence).value = "1";
       }else if(result == 1){
           document.getElementById("image" + sequence).innerHTML = "An error occurred while uploading your file. Please try again later.";
       }else if(result == 2){
           document.getElementById("image" + sequence).innerHTML = "File size too large. Images must be no larger than 1 Megabyte in size";
       }else if(result == 3){
           document.getElementById("image" + sequence).innerHTML = "Invalid file type. Only JPG, GIF, and PNG files are allowed";
       }else if(result == 4){
           document.getElementById("image" + sequence).innerHTML = "Invalid item ID specified for image";
       }else if(result == 6){
           document.getElementById("image" + sequence).innerHTML = "An SQL error has occurred. Your image has been saved to the filesystem, but the caption was not saved.";
           document.getElementById("update" + sequence).value = "1";
       }else if(result == 7){
           document.getElementById("image" + sequence).innerHTML = "You do not have permission to modify this item.";
       }
    }else{
        document.getElementById("error").innerHTML = "<font color='#ff0000'><b>An error has occurred.</b></font>";
    } 
}

function startECALogoUpload(){
        document.getElementById("eca_logo_error").innerHTML = "";
        document.getElementById("eca_logo_image").innerHTML = "Uploading...<br><img src=\"/images/i_thinking.gif\">";
}

function stopECALogoUpload(result, image, image_id, error_id, width){
    //0 = success
    //1 = upload error
    //2 = file size too large
    //3 = invalid image type
    //4 = image not tied to item ID
    //5 = invalid sequence
    //6 = SQL error
   document.getElementById(error_id).innerHTML = "";
   if(result == 0){
       document.getElementById(image_id).innerHTML = "<img src=\"" + image + "?asdf=" + Math.random()+ "\" width=\"" + width + "\">";
   }else if(result == 1){
       document.getElementById(image_id).innerHTML = "An error occurred while uploading your file. Please try again later.";
   }else if(result == 2){
       document.getElementById(image_id).innerHTML = "File size too large. Images must be no larger than 1 Megabyte in size";
   }else if(result == 3){
       document.getElementById(image_id).innerHTML = "Invalid file type. Only JPG, GIF, and PNG files are allowed";
   }else if(result == 4){
       document.getElementById(image_id).innerHTML = "Invalid item ID specified for image";
   }else if(result == 6){
       document.getElementById(image_id).innerHTML = "An SQL error has occurred. Your image has been saved to the filesystem, but the caption was not saved.";
   }else if(result == 7){
       document.getElementById(image_id).innerHTML = "You do not have permission to modify this item.";
   }
}

function startUpload(sequence){
    if(sequence > 0 && sequence < 4){
        document.getElementById("error").innerHTML = "";
        document.getElementById("image" + sequence).innerHTML = "Uploading...<br><img src=\"/images/i_thinking.gif\">";
    }else{
        document.getElementById("error").innerHTML = "<font color='#ff0000'><b>An error has occurred.</b></font>";
    }
}

function startECAUpload(sequence){
    if(sequence > 0 && sequence < 3){
        document.getElementById("error").innerHTML = "";
        document.getElementById("image" + sequence).innerHTML = "Uploading...<br><img src=\"/images/i_thinking.gif\">";
    }else{
        document.getElementById("error").innerHTML = "<font color='#ff0000'><b>An error has occurred.</b></font>";
    }
}

function stopECAItemUpload(result, image_name, sequence){
    //0 = success
    //1 = upload error
    //2 = file size too large
    //3 = invalid image type
    //4 = image not tied to item ID
    //5 = invalid sequence
    //6 = SQL error
    if(sequence > 0 && sequence < 4 && result != 5){
        document.getElementById("error").innerHTML = "";
       if(result == 0){
           document.getElementById("image" + sequence).innerHTML = "<img src=\"/images/" + image_name + "?asdf=" + Math.random() + " \" width=\"300\" border=\"0\">";
           document.getElementById("update" + sequence).value = "1";
       }else if(result == 1){
           document.getElementById("image" + sequence).innerHTML = "An error occurred while uploading your file. Please try again later.";
       }else if(result == 2){
           document.getElementById("image" + sequence).innerHTML = "File size too large. Images must be no larger than 1 Megabyte in size";
       }else if(result == 3){
           document.getElementById("image" + sequence).innerHTML = "Invalid file type. Only JPG, GIF, and PNG files are allowed";
       }else if(result == 4){
           document.getElementById("image" + sequence).innerHTML = "Invalid item ID specified for image";
       }else if(result == 6){
           document.getElementById("image" + sequence).innerHTML = "An SQL error has occurred. Your image has been saved to the filesystem, but the caption was not saved.";
           document.getElementById("update" + sequence).value = "1";
       }else if(result == 7){
           document.getElementById("image" + sequence).innerHTML = "You do not have permission to modify this item.";
       }
    }else{
        document.getElementById("error").innerHTML = "<font color='#ff0000'><b>An error has occurred.</b></font>";
    } 
}

function stopECAUpload(result, image_name, sequence){
    //0 = success
    //1 = upload error
    //2 = file size too large
    //3 = invalid image type
    //4 = image not tied to item ID
    //5 = invalid sequence
    //6 = SQL error
    if(sequence > 0 && sequence < 4 && result != 5){
        document.getElementById("error").innerHTML = "";
       if(result == 0){
           document.getElementById("image" + sequence).innerHTML = "<a href=\"/ECA/displayECAImage.php?s=" + sequence + "\" target=\"_blank\"><img src=\"/ECA/displayECAImage.php?s=" + sequence + "&asdf=" + Math.random() + "\" width=\"300\" border=\"0\"></a>";
           document.getElementById("update" + sequence).value = "1";
       }else if(result == 1){
           document.getElementById("image" + sequence).innerHTML = "An error occurred while uploading your file. Please try again later.";
       }else if(result == 2){
           document.getElementById("image" + sequence).innerHTML = "File size too large. Images must be no larger than 1 Megabyte in size";
       }else if(result == 3){
           document.getElementById("image" + sequence).innerHTML = "Invalid file type. Only JPG, GIF, and PNG files are allowed";
       }else if(result == 4){
           document.getElementById("image" + sequence).innerHTML = "Invalid item ID specified for image";
       }else if(result == 6){
           document.getElementById("image" + sequence).innerHTML = "An SQL error has occurred. Your image has been saved to the filesystem, but the caption was not saved.";
           document.getElementById("update" + sequence).value = "1";
       }else if(result == 7){
           document.getElementById("image" + sequence).innerHTML = "You do not have permission to modify this item.";
       }
    }else{
        document.getElementById("error").innerHTML = "<font color='#ff0000'><b>An error has occurred.</b></font>";
    } 
}

function prepopulateSubDeptSelectId(id, x){
    var max = document.getElementById('subDept' + x).options.length;
    for(var count=0;count<max;count++){
        if(document.getElementById('subDept'+ x).options[count].value == id){
            document.getElementById("subDept" + x).options[count].selected = true;
        }
    }
}


function prepopulateSubDeptSelect(id){
    var max = document.getElementById('subDept').options.length;
    for(var count=0;count<max;count++){
        if(document.getElementById('subDept').options[count].value == id){
            document.getElementById("subDept").options[count].selected = true;
        }
    }
}

function insertItem(action) {
    var theForm = document.getElementById('itemlisterform');
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
    
    x_insertItem(str,dummyCb);
    return true;
}

function updatePassword(action) {
    password = document.getElementById('password').value;
    passwordconfirm = document.getElementById('passwordconfirm').value;
    if (passwordconfirm != password) {
        alert('Passwords must match!');
    } else {
        if (password.length < 6) {
            alert('Password must be at least 6 characters long!');
        } else {
            x_updatePassword(password,dummyCb);
            progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
            progresswindow.close=function() {
                this.hide();
                return true;
            }
        }
    }

}

function updateDefaultAddress(action) {
    ship_id = document.getElementById('shipping_address').options[document.getElementById('shipping_address').selectedIndex].value;
    bill_id = document.getElementById('shipping_address').options[document.getElementById('billing_address').selectedIndex].value;
    x_setShipAddress(ship_id,dummyCb);
    x_setBillAddress(bill_id,dummyCb);
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }
}

function generateSubDeptSelect(dept_id, sub_id, hide, id){
    x_getDepartmentsByParentId(dept_id, sub_id, hide, id, generateSubDeptSelect_cb);
}

function generateSubDeptSelect_cb(subDepts){
    var id = subDepts['lookup_id'];
    if(id > 0){
        var select = document.getElementById("subDept" + id);
    }else{
        var select = document.getElementById("subDept");
    }
    removeOptions(select);
    addOption(select,"Select",-1); 
    for(i in subDepts){
        if(i != 'subdepartment' && i != 'lookup_id'){
            addOption(select,subDepts[i]['category'],subDepts[i]['id']);
        }
    }
    if(id > 0){
        prepopulateSubDeptSelectId(subDepts['subdepartment'], id);
    }else{
        prepopulateSubDeptSelect(subDepts['subdepartment']);
    }
    
}

function removeOptions(selectbox){
    var i;
    for(i=selectbox.options.length-1;i>=0;i--){
        selectbox.remove(i);
    }
}

function addOption(selectbox,text,value )
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

// fieldname, warningname, remainingname, maxchars
function checkFieldLength(field,wn,mc) {
    var fn = document.getElementById(field);
    var len = fn.value.length;
    if (len > mc) {
        fn.value = fn.value.substring(0,mc);
        len = mc;
    }
    document.getElementById(wn).innerHTML = len;
}

function updateDOD(action) {
    
   if(document.getElementById("radioyes").checked){
       var e = document.getElementById("dealOfDayForm").depts;
        var list = "";
        for (var i = 0; i < e.length; i++) {
            if(e[i].checked == true){
                list += e[i].value + ",";
            }
        }
        list = list.slice(0, list.length-1);
        x_updateDealOfDay(list, dummyCb);
   }else{
       x_deleteDealOfDay(dummyCb);
   }
     progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
     progresswindow.close=function() {
        this.hide();
        window.location.href='/nextStep.php';
    }
}

function checkDODyes(){
    var bool = false;
    var boxes = document.getElementById("dealOfDayForm").depts;
    for(var i = 0; i< boxes.length; i++){
        if(boxes[i].checked == true){
            bool = true;
        }
    }
    if(bool){
        document.getElementById("radioyes").checked = true;
        document.getElementById("radiono").checked = false;
    }else{
        document.getElementById("radiono").checked = true;
        document.getElementById("radioyes").checked = false;
    }
}

function uncheckAllDOD(){
var boxes = document.getElementById("dealOfDayForm").depts;
    for(var i = 0; i< boxes.length; i++){
        boxes[i].checked = false;
    }
}

function validateRegisterForm() {
    if (document.getElementById("firstname").value.length < 1) {
        alert("First Name must be set!");
        return false;
    }
    if (document.getElementById("lastname").value.length < 1) {
        alert("Last Name must be set!");
        return false;
    }
    if (document.getElementById("country").value.length < 1) {
        alert("Country must be set!");
        return false;
    }
    if (document.getElementById("email").value.length < 1) {
        alert("E-Mail must be set!");
        return false;
    }
    if (document.getElementById("email").value != document.getElementById("emailconfirm").value) {
        alert("E-Mail Addresses must match!");
        return false;
    }
    //alert(document.getElementById("password").value);
    //if (document.getElementById("password").value.length < 6) {
    //    alert("Password must be at least six characters!");
    //    return false;
    //}
    //if (document.getElementById("password").value != document.getElementById("passwordconfirm").value) {
     //   alert("Passwords must match!");
     //   return false;
    //}
    if (!isValidEmail(document.getElementById("email").value)) {
        alert("E-Mail Address is not valid!");
        return false;
    }
    return true;
}

function isValidEmail(str) {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        return (str.indexOf(".") > 1) && (str.indexOf("@") > 0);
}


function updateMyAccountInfo(action) {
    var theForm = document.getElementById('myAccountInfoForm');
    var e = theForm.elements;
    var str = "";
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        for (var i = 0; i < e.length; i++) {
            var fname=e[i].name;
            var fvalue=e[i].value;
            str += fname + "=" + encodeURI(fvalue) + "&";
        }
        
        x_updateAccountInfo(str,updateMyAccountInfo_cb);
        return true;
    }
}

function updateMyAccountInfo_cb(errors){
    if(errors.length > 0){
        alert(errors);
    }
}

function updateDefaultAddress(action) {
    ship_id = document.getElementById('shipping_address').options[document.getElementById('shipping_address').selectedIndex].value;
    bill_id = document.getElementById('shipping_address').options[document.getElementById('billing_address').selectedIndex].value;
    x_setShipAddress(ship_id,dummyCb);
    x_setBillAddress(bill_id,dummyCb);
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }
}

function setShipType(action) {
    var shiptype = document.getElementById('shiptype').options[document.getElementById('shiptype').selectedIndex].value;
    x_setShipType(shiptype,dummyCb);
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        return true;
    }

}



function setAddress(type) {
    e = document.getElementById(type);    
    id = e.options[e.selectedIndex].value;
    if (type == 'shipping_address') {
        x_getAddressById(id,setShippingAddressCb);
    } else if (type=='billing_address'){
        x_getAddressById(id,setBillingAddressCb);
    } else if (type=='address_book'){
        x_getAddressById(id,setAddressBookCb);
    }
    
    return true;
}

function setAddressBookCb(result) {
    var e = document.getElementById('x_address_book_div');
    str="";
    str += "<a href=\"javascript:editAddressEntry(" + result['id'] + ");\">Update/Delete Address</a><p>";
    str += result['email'] + "<br>";
    str += result['firstname'] + " " + result['lastname'] + "<br>";
    str += result['address'] + "<br>";
    str += result['city'] + ", " + result['state'] + "&nbsp;&nbsp;" + result['zip'] + "";
    if (result['id'] > 0) {
        e.innerHTML=str;
    } else {
        e.innerHTML="&nbsp;";
    }
}

function setShippingAddressCb(result) {
    var e = document.getElementById('x_ship_div');
    str="";
    str += result['email'] + "<br>";
    str += result['firstname'] + " " + result['lastname'] + "<br>";
    str += result['address'] + "<br>";
    str += result['city'] + ", " + result['state'] + "&nbsp;&nbsp;" + result['zip'] + "";
    if (result['id'] > 0) {
        e.innerHTML=str;
    } else {
        e.innerHTML="&nbsp;";
    }
}

function setBillingAddressCb(result,edit) {
    var e = document.getElementById('x_bill_div');
    str="";
    str += result['email'] + "<br>";
    str += result['firstname'] + " " + result['lastname'] + "<br>";
    str += result['address'] + "<br>";
    str += result['city'] + "," + result['state'] + " " + result['zip'] + "";
    if (result['id'] > 0) {
        e.innerHTML=str;
    } else {
        e.innerHTML="&nbsp;";
    }
}

function manageAddressBook(action,dl) {
    var theForm = document.getElementById('manageAddressForm');
    var e = theForm.elements;
    var str = "";

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
    
    if (dl) {
        str += "delete=1";
    }

    x_manageAddressBook(str,AddressAlertCb);

    return true;
}

function manageCC(action,dl) {
    var theForm = document.getElementById('CCForm');
    var e = theForm.elements;
    var str = "";
    

    for (var i = 0; i < e.length; i++) {
        var fname=e[i].name;
        var fvalue=e[i].value;
        str += fname + "=" + encodeURI(fvalue) + "&";
    }
   
    if (dl) {
        str += "delete=1";
    }

    x_manageCC(str,CCAlertCb);
}

function AddressAlertCb(text) {
    var action = 'SGNxbmd2YXQ=';
    if(!isNaN(text)){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            parent.addresswindow.close();
            parent.location.href=parent.location.href;
        }
    }else if(text[0]!=''){
        var str = '';
        for(x in text){
            str += text[x] + '\n';
        }
        alert(str);
   }else if(text != ""){
       var outcome = confirm(text);
       if(outcome){
            parent.addresswindow.close();
            parent.location.href='http://www.tripleclicks.com/myaccount/SOInfo.php';
        }else{
            parent.addresswindow.close();
        }
   }else{
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            parent.addresswindow.close();
            parent.location.href=parent.location.href;
        }
   }
}

function CCAlertCb(result) {
    //  0 = Successfull update
    //  1 = Missing info
    //  2 = Expired
    //  3 = Duplicate
    //  4 = Must remove from SO
    //  5 = Invalid card number
   var action = 'SGNxbmd2YXQ=';
   if(result == 0){
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            parent.ccwindow.close();
            parent.location.href=parent.location.href;
        }
   }else if(result == 1){
        alert('Missing information.');
   }else if(result == 2){
        alert('Card is expired.');
   }else if(result == 3){
        alert('Duplicate card number detected.');
   }else if(result == 4){
       var outcome = confirm('In order to delete this card, you must first remove it from your Standing Order. Do you wish to proceed?');
       if(outcome){
            parent.ccwindow.close();
            parent.location.href='http://www.tripleclicks.com/myaccount/ModifySO.php';
        }else{
            parent.ccwindow.close();
        }
   }else if(result == 5){
        alert('Invalid card number.');
   }else{
        progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
        progresswindow.close=function() {
            this.hide();
            parent.ccwindow.close();
            parent.location.href=parent.location.href;
        }
   }
}

function editSOCC(id) {
    
    ccwindow=dhtmlmodal.open('addressbox','iframe','/myaccount/ccupdate.php?so=so&act=modify&id='+id,'Modify A Credit Card','width=380px,height=425px,center=1,resize=0,scrolling=0')
    ccwindow.close=function() {
        this.hide();
        parent.location.href=parent.location.href;
        return true;
    }
}

function editCC(id) {
    
    ccwindow=dhtmlmodal.open('addressbox','iframe','/myaccount/ccupdate.php?act=modify&id='+id,'Modify A Credit Card','width=380px,height=425px,center=1,resize=0,scrolling=0')
    ccwindow.close=function() {
        this.hide();
        parent.location.href=parent.location.href;
        return true;
    }
}

function addCC(from) {
    
    ccwindow=dhtmlmodal.open('addressbox','iframe','/myaccount/ccupdate.php?act=add&from='+ from,'Add A Credit Card','width=380px,height=425px,center=1,resize=0,scrolling=0')
    ccwindow.close=function() {
        this.hide();
        parent.location.href=parent.location.href;
        return true;
    }
}

function editAddressEntry(id) {
    
    addresswindow=dhtmlmodal.open('addressbox','iframe','/myaccount/addressbook.php?act=modify&id='+id,'Modify Address Book Entry','width=380px,height=425px,center=1,resize=0,scrolling=0')
    addresswindow.close=function() {
        this.hide();
        parent.location.href=parent.location.href;
        return true;
    }
}

function addAddressEntry(from) {
    
    addresswindow=dhtmlmodal.open('addressbox','iframe','/myaccount/addressbook.php?act=add&from='+ from,'Add Address Book Entry','width=380px,height=425px,center=1,resize=0,scrolling=0')
    addresswindow.close=function() {
        this.hide();
        parent.location.href=parent.location.href;
        return true;
    }
}

function dummyCb(result) {
    return true;
}

//Adding to so with a quantity
function addToSoQty(item,qty,wl) {
    addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtoso.php?&item='+item+'&qty='+qty, 'Item Added to Standing Order', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    addcartwindow.close=function() {
        updateCart(wl);
        this.hide();
        return true;
    }
    setCartAttributes();
    return true;
}

//Adding to socart with a quantity
function addToSoCartQty(item,qty,wl) {
    addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?so=t&item='+item+'&qty='+qty, 'Item Added to Cart', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    addcartwindow.close=function() {
        updateCart(wl);
        this.hide();
        return true;
    }
    setCartAttributes();
    return true;
}

function showBidHistory(auction_id) {
    bidhistorywindow = dhtmlmodal.open('bidhistorybox','iframe','/pop_bidhistory.php?auction_id='+auction_id,'Bid History','width=275px,height=250px,center=1,resize=0,scrolling=1');
    bidhistorywindow.close=function() {
        this.hide();
        return true;
    }
    return true;
}

//Adding to cart with a quantity
function addToCartQty(item,qty,wl) {
    if (wl) {
        addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?wl=t&item='+item+'&qty='+qty, 'Item Added to Wishlist', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    } else {
        addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?item='+item+'&qty='+qty, 'Item Added to Cart', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    }
    addcartwindow.close=function() {
        updateCart(wl);
        this.hide();
        return true;
    }
    setCartAttributes();
    return true;
}

//Adding to cart with a quantity
function addToCartQtyAttr(item,qty,attr,value,wl) {
    if (wl) {
        addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?wl=t&item='+item+'&qty='+qty+'&attr='+attr+'&value='+value, 'Item Added to Wishlist', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    } else {
        addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?item='+item+'&qty='+qty+'&attr='+attr+'&value='+value, 'Item Added to Cart', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    }
    addcartwindow.close=function() {
        updateCart(wl);
        this.hide();
        return true;
    }
    setCartAttributes();
    return true;
}

//Add an encrypted string to the so 
function addToSo(str,wl) {
    addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtoso.php?q='+str, 'Item Added to Standing Order', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    addcartwindow.close=function() {
        updateCart(wl);
        this.hide();
        return true;
    }
    setCartAttributes();
    return true;
}

//Add an encrypted string to the so cart
function addToSoCart(str,wl) {
    addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?so=t&q='+str, 'Item Added to Cart', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    addcartwindow.close=function() {
        updateCart(wl);
        this.hide();
        return true;
    }
    setCartAttributes();
    return true;
}

//Add an encrypted string to the cart
function addToCart(str,wl) {
    if (wl) {
        addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?wl=t&q='+str, 'Item Added to Wishlist', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    } else {
        addcartwindow=dhtmlmodal.open('addcartbox', 'iframe', '/cart/addtocart.php?q='+str, 'Item Added to Cart', 'width=730px,height=200px,center=1,resize=0,scrolling=0')
    }
    addcartwindow.close=function() {
        updateCart(wl);
        this.hide();
        return true;
    }
    setCartAttributes();
    return true;
}



//Adding to cart with a quanity and without a modal popup
function addToCartQtyModaless(item,qty,wl) {
    if (wl) {
        x_addToWishlist(item,qty,updateCart);
    } else {
        x_addToCart(item,qty,updateCart);
    }
    x_getItemPriceByQty(item,qty,updateItemTotal); 
    return true;
}

//Callbacks
function updateItemTotal(result) {
    document.getElementById("itemprice-" + result['itemid']).innerHTML=result['price'];        

}
/////// ALl these need to get fixed to work with the wishlist
function updateCart(wl) {
    if (wl) {
        x_updateWishlist(updateCartTotals);
        //x_getCart(floatSCupdate);
    } else {
        x_updateCart(updateCartHtml);
    }
}

function updateCartHtml(result) {
    document.getElementById('cartQty').innerHTML=result['cartQty'];
    document.getElementById('cartSubtotal').innerHTML=result['cartSubtotal'];
}

function updateCartTotals(result) {
    document.getElementById('cart_subtotal').innerHTML=result['cartSubtotal'];
    document.getElementById('cart_svp').innerHTML=result['cartSvp'];
}
//End callbacks

//Do actual adding/updating/deleting from the cart with or without a modal window
function updateItem(item,qty,modal,wl) {
    if (modal) {
        addToCartQty(item,qty,wl);
    } else {
        addToCartQtyModaless(item,qty,wl);
    }
    if (qty == 0) {
        deleteRow(document.getElementById('cart-' + item));
    }
    if (wl) {
        x_updateWishlist(updateCartTotals);
    } else {
        x_updateCart(updateCartTotals);
    }
}

function moveItem(inc_item,wl) {
    var elem = document.getElementById('cartForm').elements;
    for (var i=0; i < elem.length; i++) {
        item = elem[i].name.split("-");
        var itemid = item[1];
        var qty = elem[i].value; 
        if (itemid == inc_item) {
            if (wl) {
                //Add the item to the cart
                updateItem(itemid,qty,false,false);
                //Remove the item from the wishlist
                updateItem(itemid,0,false,true);
            } else {
                //Add the item to the wishlist 
                updateItem(itemid,qty,false,true);
                //Remove the item from the cart
                updateItem(itemid,0,false,false);
            }
        }
    }

}

function validateCheckout(action) {
    document.getElementById('submit_button').disabled=true;
    var ret = false;
    ret = validateAddress("billing_");
    if (ret == false) {
        document.getElementById('submit_button').disabled=false;
        return false;
    }
    ret = validateAddress("shipping_");
    if (ret == false) {
        document.getElementById('submit_button').disabled=false;
        return false;
    }
    progresswindow=dhtmlmodal.open('progressbox', 'iframe', '/myaccount/progress.php?act='+action,  'Progress', 'width=200px,height=25px,center=1,resize=0,scrolling=0')
    progresswindow.close=function() {
        this.hide();
        parent.addresswindow.close();
    }
    updateCheckoutAddress("billing_");
    updateCheckoutAddress("shipping_");
    document.getElementById('submit_button').disabled=false;
    return ret;

}

function setPaymentMethod(text) {
    document.getElementById('paymentDiv').innerHTML=text;
}


//Loop through the shopping cart page quantities
function updateCartQty(wl) {
    var elem = document.getElementById('cartForm').elements;
    for (var i=0; i < elem.length; i++) {
        item = elem[i].name.split("-");
        var itemid = item[1];
        var qty = elem[i].value; 
        updateItem(itemid,qty,false,wl);
    }
}

function updateCurrency_cb() {
    document.location.href=document.location.href;
}

function updateCurrency() {
    x_updateCurrency(document.getElementById('currency').value,updateCurrency_cb);
}

function floatSCupdate(result) {
    document.getElementById('floatSC').innerHTML="";
    document.getElementById('floatSC').innerHTML = document.getElementById('floatSC').innerHTML + "<table border=1><tr><td colspan=3>Shopping Cart</td></tr>";
    for (i=0; i < 5; i++) {
        document.getElementById('floatSC').innerHTML = document.getElementById('floatSC').innerHTML + result[i]['headline'] + "<br>";
        document.getElementById('floatSC').style.height= "150px";
    }
    document.getElementById('floatSC').innerHTML += "</table>";
}

function deleteRow(r)
{
    var i=r.rowIndex;
    document.getElementById('cartTable').deleteRow(i);
}

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

function changeBgColor(myEvent, newBgColor)
{
if (!myEvent)
myEvent=window.event;
if (!myEvent)
return;
var firingElement=null;
// Internet Explorer
if (myEvent.srcElement)
firingElement=myEvent.srcElement;  

// Netscape and Firefox
else if (myEvent.target)
firingElement=myEvent.target;    

if (firingElement)
{
firingElement.originalBgStyle=firingElement.style["backgroundColor"];
firingElement.style["backgroundColor"]=newBgColor;
}  
}

function restoreBgColor(myEvent)
{
if (!myEvent)
myEvent=window.event;
if (!myEvent)
return;
var firingElement=null;
// Internet Explorer
if (myEvent.srcElement)
firingElement=myEvent.srcElement;  

// Netscape and Firefox
else if (myEvent.target)
firingElement=myEvent.target;    


if (firingElement)
{
firingElement.style["backgroundColor"]=firingElement.originalBgStyle;
}    
}

//document.onkeyup = arrowKey;

function arrowKey(e) {
    var shifted=false;
    var arr = document.getElementById('liveSearch').getElementsByTagName('*');
    if (arr != null && arr.length > 0) {
        if (e.keyCode == 38 || e.keyCode == 40) {
            scroll(0,0);
            var activeIndex = 0;
            for (i = 0; i < arr.length; arr++) {
                var item = arr.item(i);
                if (item.style["backgroundColor"] == "#ccffff") {
                    activeIndex = i;
                }
                item.style["backgroundColor"] = "#ffffff";
            }
            var arr = document.getElementById('liveSearch').getElementsByTagName('*');
            if (activeIndex == arr.length && e.keyCode == 40) {
                var item = arr.item(0);
                item.style["backgroundColor"] = "#ccffff"
            } else if (activeIndex == 0 && e.keyCode == 38) {
                var item = arr.item(arr.length-1);
                item.style["backgroundColor"] = "#ccffff"
            } else if (e.keyCode == 38) {
                var item = arr.item(activeIndex - 1);
                item.style["backgroundColor"] = "#ccffff"
            } else if (e.keyCode == 40) {
                var item = arr.item(activeIndex + 1);
                item.style["backgroundColor"] = "#ccffff"
            } else {
                var item = arr.item(0);
                item.style["backgroundColor"] = "#ccffff"
            }
        }
    }
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer')
      {
          var ua = navigator.userAgent;
              var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                  if (re.exec(ua) != null)
                        rv = parseFloat( RegExp.$1 );
                          }
                            return rv;
                            }



function setCartAttributes()
{
	if (! _itemAttributes) return;
	
	x_setCartAttributes(_itemID, _itemAttributes, false);
}

function loadPageJS()
{
	$('.jcarousel').jcarousel({
	    auto: 6,
		wrap: 'both',
		visible: 1,
		scroll: 1,
		animation: "slow",
		initCallback: function(carousel)
		{
		    // Disable autoscrolling if the user clicks the prev or next button.
		    carousel.buttonNext.bind('click', function() {
		        carousel.startAuto(0);
		    });
		
		    carousel.buttonPrev.bind('click', function() {
		        carousel.startAuto(0);
		    });
		
		    // Pause autoscrolling if the user moves with the cursor over the clip.
		    carousel.clip.hover(function() {
		        carousel.stopAuto();
		    }, function() {
		        carousel.startAuto();
		    });
		}
	});
}

