/***************************************************************************
*
*  File Name     : main.js
*  Version       : Initial v1.001
*  Author        : Robert Tang
*  Created       : 12/05/2011 14:04
*  Last Modified : 12/15/2011 11:23
*  Description   :
*  Function List :
*
*  History       :
*
***************************************************************************/

function noError(){
    return true;
}
//window.onerror = noError;

function switchTabMenu(id, action){
    //alert(id);
    if(action=='on'){
        //$j('#tab_menu_'+id).css('background-position', '0% -39px');
        //$j('#tab_menu_span_'+id).css('background-position', '100% -39px');
    }else{// off
        if( $j('#tab_menu_'+id).parent().get(0).id !='current' ){ // if is not selected tab
            //$j('#tab_menu_'+id).css('background-position', '0% 0');
            //$j('#tab_menu_span_'+id).css('background-position', '100% 0');
        }
    }
}

function activeTabview(max_tabNum) { // activate tabView
    var tabView = new YAHOO.widget.TabView('tab_product_filter');
    document.getElementById('yui-content').style.display="block";

    var cookieTabNum=0;
    cookieTabNum=YAHOO.util.Cookie.get("tabcookie_product_filter");

    if(parseInt(max_tabNum) > parseInt(cookieTabNum)){
        tabView.set("activeTab", tabView.getTab(cookieTabNum));
    }

    //when a Tab changes, set the cookie:
    tabView.on("activeTabChange", function(o) {
        YAHOO.util.Cookie.set("tabcookie_product_filter", this.getTabIndex(o.newValue));
    });
};


function jsGetSearchResultOfCategory(keyword, catId){
    //alert(keyword +', '+catId);
    if(keyword!=''){
        $j.ajax({
            type: "GET",
            url: "/cart.php?m=ajax_get_search_result_category",
            data: {
                keyword:    keyword,
                c:          catId
            },
            beforeSend: function(){
                //$j('#ajax_loader_coupon').show();
            },
            success: function(data){
                //var count       =data.match(/<itemCount>([\w\W]*)<\/itemCount>/)[1];
                //$j('#top_cart_item_num').html(count);

                $j('#left_result_category').html(data);
            }
        });
    }
}

function jsGetSearchResultOfFilter(keyword, catId, pageNum, noLimit, limitNum, sort, filterJSON, priceRangeId){
    //console.log(filterJSON);

    if(keyword!=''){
        $j.ajax({
            type: "POST",
            url: "/cart.php?m=ajax_get_search_result_filter",
            data: {
                keyword:    keyword,
                c:          catId,
                page:       pageNum,
                noLimit:    noLimit,
                ln:         limitNum,
                sort:       sort,
                f:          filterJSON,
                pr:         priceRangeId
            },
            beforeSend: function(){
                $j('#ajaxloader_filter').show();
            },
            success: function(data){
                var tabCount=data.match(/<tabCount>([\w\W]*)<\/tabCount>/)[1];
                //$j('#top_cart_item_num').html(count);

                var content =data.match(/<content>([\w\W]*)<\/content>/)[1];
                document.getElementById('faceted-search-region').innerHTML= content;

                setTimeout(function(){activeTabview(tabCount)},100);
                $j('#faceted-search-region').css("padding","20px 0");
                $j('#faceted-search-region').css("width","100%");

            }
        });
    }
}

function jsAddCouponCode(theForm){
    var code=theForm.couponCode.value;
    if(code!=''){
        $j.ajax({
            type: "POST",
            url: "/cart.php?m=ajaxAddCouponCode",
            data: {code: code},
            beforeSend: function(){
                $j('#msg_coupon').html('');
                $j('#bt_add_coupon').hide();
                $j('#ajax_loader_coupon').show();
            },
            success: function(data){
                //var count       =data.match(/<itemCount>([\w\W]*)<\/itemCount>/)[1];
                //$j('#top_cart_item_num').html(count);
                $j('#ajax_loader_coupon').hide();
                $j('#bt_add_coupon').show();
                $j('#msg_coupon').html(data);
                jsSubmitRightsideCart(); // update card info
            }
        });
    }else{
        $j('#msg_coupon').html("<font style='color:red;'>Please enter a coupon code.</font>");
        theForm.couponCode.focus();
    }

    return false;
}

function jsSubmitRightsideCart(){
    $j.ajax({
        type: "POST",
        url: "/cart.php?m=ajaxUpdateCart",
        data: $j('#fm_rightside_cart').serialize(),
        beforeSend: function(){
            $j('#ajax_loader_rightside').css('line-height', $j('#cartDetails').height()+'px' );
            $j('#ajax_loader_rightside').show();
        },
        success: function(data){
            var count       =data.match(/<itemCount>([\w\W]*)<\/itemCount>/)[1];
            $j('#top_cart_item_num').html(count);

            var cartContent =data.match(/<cartContent>([\w\W]*)<\/cartContent>/)[1];
            $j('#cart_rightside').html(cartContent);
        }
    });
    return false;
}

function jsCheckAccountStatus(email){
    $j.ajax({
        type: "POST",
        url: "/cart.php?m=ajaxAccountStatus",
        data:{email: email},
        success: function(data){
            //var count       =data.match(/<itemCount>([\w\W]*)<\/itemCount>/)[1];
            alert(data);
            return data;
        }
    });
}

function jsValidateLoginForm(email_input, password_input){
    if(document.getElementById(email_input).value==''){
        alert("Please enter your email address.");
        document.getElementById(email_input).focus();
        return false;
    }

    if(document.getElementById(password_input).value==''){
        alert("Please enter your password.");
        document.getElementById(password_input).focus();
        return false;
    }
    return true;
}

var shippingArr=new Array();// global variable with function of 'jsCopyBillingAddress()'
function jsCopyBillingAddress(checkbox){
    if(shippingArr.length<1){// first time run, store customer's shipping address
        shippingArr=[
            {shipFName:''}
        ];

        shippingArr['shipFName']=document.getElementById('shipFName').value;
        shippingArr['shipLName']=document.getElementById('shipLName').value;
        shippingArr['shipCompany']=document.getElementById('shipCompany').value;
        shippingArr['shipCountry']=document.getElementById('shipCountry').value;
        shippingArr['shipAddress1']=document.getElementById('shipAddress1').value;
        shippingArr['shipAddress2']=document.getElementById('shipAddress2').value;
        shippingArr['shipCity']=document.getElementById('shipCity').value;
        shippingArr['ship_usState']=document.getElementById('ship_usState').value;
        shippingArr['ship_caProvince']=document.getElementById('ship_caProvince').value;
        shippingArr['shipZip']=document.getElementById('shipZip').value;
        shippingArr['shipPhone']=document.getElementById('shipPhone').value;

    }

    if(checkbox.checked){// copy billing address to shipping
        document.getElementById('shipFName').value=document.getElementById('billFName').value;
        document.getElementById('shipLName').value=document.getElementById('billLName').value;
        document.getElementById('shipCompany').value=document.getElementById('billCompany').value;
        document.getElementById('shipCountry').value=document.getElementById('billCountry').value;
        document.getElementById('shipAddress1').value=document.getElementById('billAddress1').value;
        document.getElementById('shipAddress2').value=document.getElementById('billAddress2').value;
        document.getElementById('shipCity').value=document.getElementById('billCity').value;
        document.getElementById('ship_usState').value=document.getElementById('bill_usState').value;
        document.getElementById('ship_caProvince').value=document.getElementById('bill_caProvince').value;
        document.getElementById('shipZip').value=document.getElementById('billZip').value;
        document.getElementById('shipPhone').value=document.getElementById('phone').value;


    }else{// restore shipping address
        document.getElementById('shipFName').value=shippingArr['shipFName'];
        document.getElementById('shipLName').value=shippingArr['shipLName'];
        document.getElementById('shipCompany').value=shippingArr['shipCompany'];
        document.getElementById('shipCountry').value=shippingArr['shipCountry'];
        document.getElementById('shipAddress1').value=shippingArr['shipAddress1'];
        document.getElementById('shipAddress2').value=shippingArr['shipAddress2'];
        document.getElementById('shipCity').value=shippingArr['shipCity'];
        document.getElementById('ship_usState').value=shippingArr['ship_usState'];
        document.getElementById('ship_caProvince').value=shippingArr['ship_caProvince'];
        document.getElementById('shipZip').value=shippingArr['shipZip'];
        document.getElementById('shipPhone').value=shippingArr['shipPhone'];
    }

    jsChangeCountry(document.getElementById('shipCountry').value, 'ship_usState', 'ship_caProvince', 'ship_state_label');
}

function jsChangeCountry(country, usState,  caProvince, label){
    if(country=='CA'){
        document.getElementById(usState).style.display='none';
        document.getElementById(caProvince).style.display='block';
        document.getElementById(label).innerHTML='Province';

    }else{
        document.getElementById(caProvince).style.display='none';
        document.getElementById(usState).style.display='block';
        document.getElementById(label).innerHTML='State';
    }
}

function jsRegisterProductSelectedOption(formID, pID){ // register listener on change option elements
    if(formID!=''){
        var which = document.getElementById(formID);
    }else{
        var which = document.productForm;
    }

    for(i=0; i<which.length; i++){
        var tempobj=which.elements[i];
        if(tempobj.name.substring(0,7)=='options' || tempobj.name.substring(0,16)=='checkbox_options' || tempobj.name.substring(0,4)=='gnm_') {
            if(tempobj.addEventListener){
                tempobj.addEventListener("change",  function(){ ajaxCalcualatePrice(pID, $j('#quantity_text_input').val()) }, 0 );
            }else if(tempobj.attachEvent){
                if(tempobj.type=='checkbox'){// checkbox
                    $j("input[name='"+tempobj.name+"']").click(function() {
                        ajaxCalcualatePrice(pID, $j('#quantity_text_input').val())
                    });
                }else{
                    tempobj.attachEvent("onchange", function(){ ajaxCalcualatePrice(pID, $j('#quantity_text_input').val()) }, 0 );
                }
            }else{
                tempobj.onChange=new Function("ajaxCalcualatePrice("+pID+", "+$j('#quantity_text_input').val()+")");
            }

            //alert('option object registered... 03 object:'+ tempobj.name);
        }
    }// end for

    //alert('option object registered...');
    ajaxCalcualatePrice(pID, $j('#quantity_text_input').val());

    return true;
}

function ajaxCalcualatePrice(productId, qty){
    $j('#customize-size-ajaxloader').show();
    $j('#bt-addToCart').attr("disabled", true);

    var dimension   =getDimensionStr();
    var extraField  = (document.productForm.extraField) ? document.productForm.extraField.value : "";
    var time        = new Date().getTime();

    $j.get('/ajax_product_detail.php',{
            m:              'all',
            p:              productId,
            optionStr:      getSelectedOptions('productForm'),
            extraField:     extraField,
            dimensionStr:   dimension,
            utilityIndex:   -1,
            force       :   time
        },
        function(data){
            var json=$j.parseJSON(data);
            //var finalPrice=(makeMoneyStr(json.price_dollars, json.price_cents)*qty);
            var finalPrice=(json.price);//*qty
            finalPrice=finalPrice.toFixed(2);

            $j('#customize-size-ajaxloader').hide();
            $j('#bt-addToCart').removeAttr("disabled");
            $j('#final-price').html(finalPrice);
        }
    );
}

function ajaxCalcualtePriceByOption(productId, qty){
    //alert(parameters);return false;

    $j('#customize-size-ajaxloader').show();
    $j('#bt-addToCart').attr("disabled", true);

    var extraField = (document.productForm.extraField) ? document.productForm.extraField.value : "";
    $j.get('/ajax_product_detail.php',{
            m:              'base',
            p:              productId,
            optionStr:      getSelectedOptions('productForm'),
            extraField:     extraField,
            utilityIndex:   -1
        },
        function(data){
            var json=$j.parseJSON(data);
            var finalPrice=(makeMoneyStr(json.price_dollars, json.price_cents)*qty);
            finalPrice=finalPrice.toFixed(2);

            $j('#customize-size-ajaxloader').hide();
            $j('#bt-addToCart').removeAttr("disabled");
            $j('#final-price').html(finalPrice);
        }
    );
}

function ajaxCalcualatePriceBySize(productId, qty){
    // dimensionStr sample: '0:0:0:0:0:0:f'
    // [valMap.width_whole,valMap.width_frac,   valMap.height_whole,valMap.height_frac, valMap.length_whole,valMap.length_frac,     valMap.is3Sided ? 't' : 'f']

    $j('#customize-size-ajaxloader').show();
    $j('#bt-addToCart').attr("disabled", true);

    var dimension=getDimensionStr()
    $j.get('/ajax_product_detail.php',{
            m:  'dimension',
            p:  productId,
            dimensionStr: dimension,
            utilityIndex:-1
        },
        function(data){
            var json=$j.parseJSON(data);
            var finalPrice=(makeMoneyStr(json.price_dollars, json.price_cents)*qty);
            finalPrice=finalPrice.toFixed(2);

            $j('#customize-size-ajaxloader').hide();
            $j('#bt-addToCart').removeAttr("disabled");
            $j('#final-price').html(finalPrice);
        }
    );
}

function getSelectedOptions(formID){
    var myoptions = '';

    if(document.images) {
        if(formID!=''){
            var which = document.getElementById(formID);
        }else{
            var which = document.productForm;
        }

        for(i=0;i<which.length;i++) {
            var tempobj=which.elements[i];
            if(tempobj.name.substring(0,7)=='options' || tempobj.name.substring(0,16)=='checkbox_options'){
                var fieldType = tempobj.type;
                if(fieldType=='select-one'){
                    if(tempobj.selectedIndex > -1){
                        var myval = tempobj[tempobj.selectedIndex].value;
                        myoptions += ',' + myval;
                    }
                } else if(fieldType=='radio' || fieldType=='checkbox'){
                    if(tempobj.checked){
                        var myval = tempobj.value;
                        myoptions += ',' + myval;
                    }
                } else {
                    //ignore
                }
            }
        }
   }

   return myoptions;
}

function getUtilityIndex(){
    if (!$j('#utility_select_input')){
        return -1;
    }else{
        return $j('#utility_select_input');
    }
}

// Generate a dimension str from the current dimension control settings
function getDimensionStr(){
    //if (!gnm.haveDimensions) return '0:0:0:0:0:0:f'  // disabled by Robert 1/21/2011

    var valMap = getControlValueMap()
    var a = [valMap.width_whole,valMap.width_frac,valMap.height_whole,valMap.height_frac,valMap.length_whole,valMap.length_frac,valMap.is3Sided ? 't' : 'f',valMap.track2track ? 't' : 'f']
    var s = a.join(':')
    return s
}

// Return an object mapping input ids to values.  Missing values are set to 0.
function getControlValueMap(){
    var quantity    = $j('#quantity_text_input').val();

    var width_whole = $j('#width_whole_text_input').val();
    var width_frac  = $j('#width_frac_select_input').val();

    var height_whole= $j('#height_whole_text_input').val();
    var height_frac = $j('#height_frac_select_input').val();

    var length_whole= $j('#length_whole_text_input').val();
    var length_frac = $j('#length_frac_select_input').val();

    var is3Sided    = $j('#is_3_sided_checkbox_input').is(':checked');
    var track2track = $j('#track_to_track_checkbox_input').is(':checked');

    return { quantity: ((quantity == null) ? 0 : quantity),
             width_whole: ((width_whole == null) ? 0 : width_whole),
             width_frac: ((width_frac == null) ? 0 : width_frac),
             height_whole: ((height_whole == null) ? 0 : height_whole),
             height_frac: ((height_frac == null) ? 0 : height_frac),
             length_whole: ((length_whole == null) ? 0 : length_whole),
             length_frac: ((length_frac == null) ? 0 : length_frac),
             is3Sided: is3Sided,
             track2track: track2track
    }
}

function makeMoneyStr(dollars,cents){
    cents = ['',cents].join('')
    while (cents.length < 2) cents = '0' + cents
    return [dollars,'.',cents].join('')
}

function onlyAllowNumberKey(e, withdot){ // by Robert
    var obj=e.srcElement || e.target;
    var dot=obj.value.indexOf(".");
    var key=e.keyCode;

    if(key==0){
        key=e.which;
    }

    //alert(key);
    if(key==8 || key==9 || key==116 || (key>=37 && key<=40)){
        return true;
    }

    if(key<=57 && key>=48){ // for integer
        if(dot==-1){ // deny dot
            return true;
        }else if(obj.value.length<=dot+2){ // two decimal
            return true;
        }
    }else if((key==46) && dot==-1 && withdot==1){ //decimal
        return true;
    }

    return false;
}

function jsStoreAddItem(eid, qty){ // by Robert
    if(eid==''){
        alert("Equipment ID is mission.");
    }

    if(qty<1){
        qty=0;
    }

    $j.ajax({
        type: "POST",
        dataType:'html',
        url: "cart.php",
        data: "m=ajax_store_additemtocart&eid="+eid+"&qty="+qty,

        beforeSend:function(){
            //alert('beforeSend');
            $j('#num_'+eid).hide();
            $j('#ajaxloader_num_'+eid).show();
            $j('#ajax_loader').show();

        },
        success: function(html){
            var count=html.match(/<itemCount>([\w\W]*)<\/itemCount>/)[1];
            var subtotal=html.match(/<subtotal>([\w\W]*)<\/subtotal>/)[1];

            $j('#ajaxloader_num_'+eid).hide();
            $j('#num_'+eid).show();

            $j('#ajax_loader').hide();
            $j('#itemCount').html(count);
            $j('#subtotal_info').html(subtotal);
        }
    });
}



