
var StoreManager = function(){
   return {
      refreshUserCart :function() {
        try{
         Yahoo_showLoading("Refreshing your cart, Please wait.");
         var url = g_service_path + "/store/refresh_user_cart";
         var small_cart = $F("small_cart");
         var sms_flow = ""
         if($("sms_flow")){
           sms_flow  = $F("sms_flow"); 
         }
         ajaxCall(url, {parameters: $H({small_cart : small_cart,sms_flow : sms_flow}).toQueryString(),onComplete : Yahoo_hideLoading});
         }catch(e){}
      },
      /**
       * function to add items in the cart
       * @param {Object} product_id
       * @param {Object} quantity
       */
      addToCart :function(product_id,quantity){
        try{
          var onCompleteAction = function(){
            //Yahoo_hideLoading();
            //StoreManager.refreshUserCart();
          };
          url = g_service_path + "/store/add_to_cart_ajax";
          Yahoo_showLoading('Adding item to Your Cart');
          ajaxCall(url, {
            parameters: $H({
              id : product_id,
              quantity: quantity
            }).toQueryString(),
            onComplete: onCompleteAction
          });
          /*,
            onFailure : function(){Yahoo_hideLoading();alert('That item appears to have gone out of stock before you were able to add it to your cart.\n\nPlease refresh this page.')}*/
        }catch(e){}
      },


      /**
       * function to add items in the cart
       * @param {Object} variation_id
       * @param {Object} quantity
       */
      addVariationToCart :function(variation_id,quantity){
        try{
          var onCompleteAction = function(){
            //Yahoo_hideLoading();
            //StoreManager.refreshUserCart();
          };
          url = g_service_path + "/store/add_to_cart_ajax";
          Yahoo_showLoading('Adding item to Your Cart');
          ajaxCall(url, {
            parameters: $H({
              variation : variation_id,
              quantity: quantity
            }).toQueryString(),
            onComplete: onCompleteAction
          });
          /*,
            onFailure : function(){Yahoo_hideLoading();alert('That item appears to have gone out of stock before you were able to add it to your cart.\n\nPlease refresh this page.')}*/
        }catch(e){}
      },

      /**
       * function to render new viewes
       * @param {Object} view_to_rend
       * @param {Object} category
       * @param {Object} sort_by[optional]
       */
      changeView : function(view_to_rend, category,sort_str){
        try{
          var onCompleteAction = function(){
            Yahoo_hideLoading();
          };
          var sort_by ="";
          if(sort_str){
            sort_by = sort_str;
          }
          url = g_service_path + "/dstore/category_ajax";
          Yahoo_showLoading('Processing');
          ajaxCall(url, {
            parameters: $H({
              view_to_rend: view_to_rend,
              id : category,
              sort_by : sort_by
            }).toQueryString(),
            onComplete: onCompleteAction
          });
        }catch(e){}
      },
      sort : function(sort_by,search_term,view_as) {

        try{
          /*var current_url = document.location.href;
          if(current_url.indexOf('?') != -1) {
            current_url = current_url.substr(0, current_url.indexOf('?'));
          }
          current_url = current_url + "?sort_by=" + sort_by +"&view_as="+view_as;
          if (search_term != "") {
            current_url = current_url + "&search_term=" + search_term;
          }
          document.location.href = current_url;*/
          document.frm_srt_and_view.submit();
       }catch(e){ }
      },
       /**
     * Function to validate the advanced search option
     */
    validateAdvSearch : function(formObj){
      try{
        var atLeastOneSelected = false;
        var isValid = true;

        var priceFrom = formObj.price_from.value;
        var priceTo   = formObj.price_to.value;
        var dateFrom  = formObj.date_from.value;
        var dateTo    = formObj.date_to.value;

        priceFrom = priceFrom.strip();
        priceTo   = priceTo.strip();
        dateFrom = dateFrom.strip();
        dateTo   = dateTo.strip();

        CEManager.evt_showErrorMsg('adv_search_opt', '');
        CEManager.evt_showErrorMsg('adv_search_price_from', '');
        CEManager.evt_showErrorMsg('adv_search_price_to', '');
        CEManager.evt_showErrorMsg('adv_search_date_from', '');
        CEManager.evt_showErrorMsg('adv_search_date_to', '');

        Element.hide('adv_search_opt');
        Element.hide('adv_search_price_from');
        Element.hide('adv_search_price_to');
        Element.hide('adv_search_date_from');
        Element.hide('adv_search_date_to');

        if(priceFrom.length !=0){
          if(!isNum(priceFrom)){
            CEManager.evt_showErrorMsg('adv_search_price_from', 'Please enter number only');
            Element.show('adv_search_price_from');
            isValid = false;
          }
          atLeastOneSelected = true;
        }

        if(priceTo.length !=0){
          if(!isNum(priceTo)){
            CEManager.evt_showErrorMsg('adv_search_price_to', 'Please enter number only');
            Element.show('adv_search_price_to');
            isValid = false;
          }
          atLeastOneSelected = true;
        }

        if((priceFrom.length !=0 && priceTo.length !=0 ) && (parseInt(priceTo) < parseInt(priceFrom)) && (isValid)){
          CEManager.evt_showErrorMsg('adv_search_price_from', 'Please enter valid price range');
          Element.show('adv_search_price_from');
          isValid = false;
        }

        if(dateFrom.length != 0 && dateFrom == "mm/dd/yyyy"){
          formObj.date_from.value = "";
          dateFrom = '';
        }
        if(dateTo.length != 0 && dateTo == "mm/dd/yyyy"){
          formObj.date_to.value = "";
          dateTo = '';
        }

        if(dateFrom.length != 0){
          if (isNaN(new Date(formObj.date_from.value))){
            CEManager.evt_showErrorMsg('adv_search_date_from', 'Please select valid date');
            Element.show('adv_search_date_from');
            isValid = false;
          }
          atLeastOneSelected = true;
        }

        if(dateTo.length != 0){
          if (isNaN(new Date(formObj.date_to.value))){
            CEManager.evt_showErrorMsg('adv_search_date_to', 'Please select valid date');
            Element.show('adv_search_date_to');
            isValid = false;
          }
          atLeastOneSelected = true;
        }
        var criteria = $F(formObj.criteria);
            criteria = criteria.strip();
        if(criteria.length >0){
          atLeastOneSelected = true;
        }
        if(isValid && atLeastOneSelected){
          formObj.submit();
          return true;
        }else if(atLeastOneSelected == false){
          CEManager.evt_showErrorMsg('adv_search_opt', 'Please select at least one search criteria.');
          Element.show('adv_search_opt');
        }
        dateFrom = dateFrom.length == 0 ? 'mm/dd/yyyy' : dateFrom;
        dateTo = dateTo.length == 0 ? 'mm/dd/yyyy' : dateTo;

        formObj.date_from.value = dateFrom;
        formObj.date_to.value = dateTo;
        return false;
      }catch(e){}
    },

    /**
     * Function to fetch result for advance search
     */
    submitAdvSearch: function(formObj){
      try{
        return StoreManager.validateAdvSearch(formObj);
      }catch(e){}
    },
    
    /**
     * function to change view of items
     */
    viewAs: function(id,search_term){
      try{

         var current_url = document.location.href;
          if(current_url.indexOf('?') != -1) {
            current_url = current_url.substr(0, current_url.indexOf('?'));
          }
          
          var view_as = $(id).value;          
          current_url = current_url + '?view_as=' + view_as;

          if(search_term != '') {
              current_url+= '&search_term=' + search_term;
          }
          
          //document.location.href = current_url;
          document.frm_srt_and_view.submit();

      }catch(e){ }
    },

    /*
     *  function to validate payment (credit card / paypal)
     */
    validatePayment: function (current_month, current_year, type){
        try{
            
            if (type == "paypal"){
                document.store_checkout_payment.action = g_service_path + "/dstore/confirm_paypal";
                document.store_checkout_payment.submit();
                return true;
            }
            else if (type == "cc"){
                if (StoreManager.validate_checkout(current_month,current_year,type)) {
                    document.store_checkout_payment.action = g_service_path + "/dstore/confirm";
                    document.store_checkout_payment.submit();
                } else {
                  return false;
                }

            }
            
        }
        catch(e){}
    },

    /**
     * function to validate checkout page
     */
     validate_checkout : function (current_month,current_year,type) {
      try{

         var promo_code = $('promo_code');
         var is_promo_valid = $('is_promo_valid');

         if(promo_code && promo_code.value != "" && (is_promo_valid.value == "N" ||
              is_promo_valid.value == "")) {

           if(is_promo_valid.value == "") {
            alert("Please recheck the promotion code you have entered");
           } else {
            alert("Sorry, the promotion code you entered is not valid");
           }
           
           promo_code.focus();
           return false;
         }

         // check if only Printable Games product(s) are there.
         var is_only_PG  = $("chk_validation_restriction").getAttribute("isonlyPG");

         var billing_address_fn = $("billing_address_first_name");
         var billing_address_ln = $("billing_address_last_name");

         if(is_only_PG == 'false') {
             var billing_address_ad = $("billing_address_address");
             var billing_address_city = $("billing_address_city");
             var billing_address_zip = $("billing_address_zip");
             var billing_address_tele = $("billing_address_telephone");
             var billing_address_c = $("billing_address_country");

             if(billing_address_c.value == '1') {
               $('billing_address_state').value = $('billing_address_state_sel').value;               
             }
             var billing_address_state = $("billing_address_state");

             var shipping_address_fn = $("shipping_address_first_name");
             var shipping_address_ln = $("shipping_address_last_name");
             var shipping_address_ad = $("shipping_address_address");
             var shipping_address_city = $("shipping_address_city");
             var shipping_address_zip = $("shipping_address_zip");
             var shipping_address_tele = $("shipping_address_telephone");
             var shipping_address_c = $("shipping_address_country");
             
             if(shipping_address_c.value == '1') {
               $('shipping_address_state').value = $('shipping_address_state_sel').value;
             }
             var shipping_address_state = $("shipping_address_state");
             var needs_shipping = false;
             
         }
         
         var credit_month = $('credit_month');
         var credit_year = $('credit_year');
         var credit_card_number = $('credit_card_number');
         var security_code = $('security_code');
                  
        //(1). Validate Credit Card details :: START  //
         if (type != "paypal") {

           credit_month = $('credit_month');
           credit_year = $('credit_year');
           if((parseInt(current_year) == parseInt(credit_year.value)) && (parseInt(credit_month.value) < parseInt(current_month))){
             alert("The expiration date entered for the credit card is invalid. Please check the date and try again.");
             credit_month.focus();
             return false;
           }
           if(!StoreManager.alertFunction(credit_card_number,'10','Credit card number')){
             return false;
           }
           if(!StoreManager.alertFunction(security_code,'3','Security code')){
             return false;
           }
         }
         //(1). Validate Credit Card details :: END //

         if(!StoreManager.alertFunction(billing_address_fn,'0','First name')){
           return false;
         }
         if(!StoreManager.alertFunction(billing_address_ln,'0','Last name')){
           return false;
         }

         if(is_only_PG == 'false') {
             
             /* Add default validations */
             if(!StoreManager.alertFunction(billing_address_ad,'0','Billing address')){
               return false;
             }

             if(!StoreManager.alertFunction(billing_address_city,'0','City')){
               return false;
             }
             
             if(!StoreManager.alertFunction(billing_address_state,'0','State')){
               if(billing_address_c.value == '1') {
                 $('billing_address_state_sel').focus();
               }
               return false;
             }

             if(!StoreManager.alertFunction(billing_address_zip,'0','Zip Code', true)){
               return false;
             }
             else if( billing_address_c.value == '1' && !ApplicationManager.validateZipcode(billing_address_zip.value)){
               alert(ERR_MSG["INV_ZIP"]);
               billing_address_zip.focus();
               return false;
             }

             if(!StoreManager.alertFunction(billing_address_tele,'0','Phone')){
               return false;
             }

             // Validations for shipping country not to be USA, if billing address has USA as the country
             // and user has selected shipping address to be same as billing address
             if(billing_address_c.value != '1') {
               needs_shipping = $('shipping_info_opt').getAttribute('needs_shipping');
               if(needs_shipping == 'true' && !($('use_diff_shipping').checked)) {
                 alert('Shipping is available to USA only. Please provide shipping address of USA only.');
                 $('use_diff_shipping').checked = true;
                 shipping_address_fn.focus();
                 $('shipping_address').show();
                 return false;
               }
             }
             //-- :: END

             if ($('use_diff_shipping').checked) {
               if(!StoreManager.alertFunction(shipping_address_fn,'0','First name')){
                return false;
                }
                if(!StoreManager.alertFunction(shipping_address_ln,'0','Last name')){
                  return false;
                }
                if(!StoreManager.alertFunction(shipping_address_ad,'0','Shipping address')){
                  return false;
                }
                if(!StoreManager.alertFunction(shipping_address_city,'0','City')){
                  return false;
                }
                if(!StoreManager.alertFunction(shipping_address_state,'0','State')){
                  if(shipping_address_c.value == '1') {
                    $('shipping_address_state_sel').focus();
                  }
                  return false;
                }
                if(!StoreManager.alertFunction(shipping_address_zip,'0','Zip code', true)){
                  return false;
                }else if(shipping_address_c.value == '1' && !ApplicationManager.validateZipcode(shipping_address_zip.value)){
                  alert(ERR_MSG["INV_ZIP"]);
                  shipping_address_zip.focus();
                  return false;

                }
                if(!StoreManager.alertFunction(shipping_address_tele,'0','Phone')){
                  return false;
                }
             }
            /* Add default validations : END*/
         }

         return true;
         
          }catch(e){}

        },

        alertFunction : function(obj, len, txt_to_app, dontCheckAlpha){
          try{
            
            if(!dontCheckAlpha){
              dontCheckAlpha = false;
            }
              var returned_val = StoreManager.chkForConditions(obj.value,len, dontCheckAlpha);
              if(!returned_val[0]){
                if(returned_val[1] == "BLANK"){
                  obj.focus();
                  alert(txt_to_app +" can't be blank");
                  return false;
                }else if(returned_val[1] == "NAN"){
                  obj.focus();
                  alert(txt_to_app+" can't be characters");
                  return false;
                }else if(returned_val[1] == "SL"){
                  obj.focus();
                  alert(txt_to_app+" can't be less then "+len+" numbers");
                  return false;
                }
              }else{
                return true;
              }
          }catch(e){}
        },
        /**
         * function to check for condition for given value
         * @param {Object} val
         * @param {Object} len_to_chk
         */
        chkForConditions : function(val,len_to_chk, dontCheckAlpha){
          try{
            //alert("chk "+val)
            var return_val =[];
            if(val != ""){
              if (parseInt(len_to_chk) > 0) {
                if(isNaN(val) && !dontCheckAlpha){
                  return_val[0] = false;
                  return_val[1] = "NAN";
                }else if(val.length < len_to_chk){
                  return_val[0] = false;
                  return_val[1] = "SL";
                }else{
                  return_val[0] = true;
                  return_val[1] = "";
                }
              }else{
                return_val[0] = true;
                return_val[1] = "";
              }
            }else{
              return_val[0] = false;
              return_val[1] = "BLANK";
            }
            return return_val;
          }catch(e){}
        },
        shippingShowHide : function(code, needs_shipping){
          try{
            if(code=="BS" || needs_shipping == "false"){
              Element.hide("checkout_check_div");
              Element.hide("shipping_address");
              Element.hide("shipping_address_cont");
              $("use_diff_shipping").checked = false;
            }else{
              Element.show("checkout_check_div");
              Element.show("shipping_address");
              Element.show("shipping_address_cont");
              $("use_diff_shipping").checked = true;
            }
          }catch(e){}
        },
        fetchShippingOptions : function(){
          try{
           url = g_service_path + "/dstore/fetch_shipping_types";
            MS.showWait('attribution_event_consultant', 'center');

            ajaxCall(url, {
              parameters: $H({
                attribution_event_consultant : $('attribution_event_consultant').value
              }).toQueryString()
              ,onComplete: MS.hideWait()
            });
          }catch(e){}
        },
        productEditCreate : function(event_id){
          try{
            var tpl = new Template("<div class='hd gray'>#{title}</div><div class='bd' id='#{body_id}'></div><div class='ft'></div>");
            var cont = MS.Dom.create("div", {
              "id": "products_edit_popup",
              "style": "display:none"
            });
            cont.innerHTML = tpl.evaluate({
              "title": "Edit",
              "body_id": "products_edit_popup_body"
            });
            //add to body
            document.body.appendChild(cont);
            cont  = null;
            Yahoo_showLoading();
            var onComplete = function(){
              Yahoo_hideLoading();
            };
            ajaxCall(g_service_path + "/dstore/promoted_products_edit", {
              parameters: {
                event_id: event_id,
                onComplete: onComplete
              }
            });
          }catch(e){}
        },
        productEditShow : function(){
          try{
            Yahoo_hideLoading();
            var productEditId = "products_edit_popup";
            YAHOO.util.Dom.setStyle(productEditId, "display", "block");
            var productEditPopup = new YAHOO.widget.Dialog(productEditId, {
              width: "500px",
              zIndex: 275,
              fixedcenter: true,
              visible: false,
              modal: true,
              postmethod: "manual",
              constraintviewport: true
            });
            productEditPopup.render();
            productEditPopup.show();
            productEditPopup.center();

            var handleCancel = function(){
              productEditPopup.destroy();
            };
            var handleSave = function(){
              try{
                Yahoo_showLoading();
                var onComplete = function(){
                  Yahoo_hideLoading();
                  handleCancel();
                  window.location.reload();
                };
                var params = $H(Form.serialize($("prometed_product"), true));
                ajaxCall(g_service_path + "/dstore/promoted_products_save", {
                  parameters: params,
                  onComplete: onComplete
                });
              }catch(e){}
            };
              YAHOO.util.Event.on("promoted_product_save", "click", handleSave, productEditPopup, true);
              productEditPopup.hide = handleCancel;
          }catch(e){}
        },
        updateShoopingCart : function(){
          try{
            var params = $H(Form.serialize($('shopping_cart'), true));
                  new Ajax.Updater('items', g_service_path + '/store/update_cart_ajax',
                  {asynchronous:true, evalScripts:true,
                  onLoading:function(request){Yahoo_showLoading('Updating Your Cart');},
                  onComplete:function(request){Yahoo_hideLoading();StoreManager.refreshUserCart();},
                  onFailure:function(request){alert('Sorry, the server seems to be too busy! Please retry after some time.')},
                  parameters:params});
          }catch(e){}
        },
        addProduct : function(p_id){
          try{
            new Ajax.Updater('items', g_service_path + '/store/add_to_cart_ajax/'+p_id+'?from_page=DC',
                {asynchronous:true, evalScripts:true,
                 onLoading:function(request){Yahoo_showLoading('Adding item to Your Cart');},
                 onComplete:function(request){Yahoo_hideLoading();},
                 onFailure:function(request){Yahoo_hideLoading();alert('That item appears to have gone out of stock before you were able to add it to your cart.\n\nPlease refresh this page.')},
                 parameters:Form.serialize($('form_add_to_cart_'+p_id))}); return false;
          }catch(e){}
        },
        checkoutSMSInvites : function(year, month){
          try{
            if (StoreManager.validateCreditCardInfo(year, month)) {
              var form = $("send_sms_invites_cc_form");
              var params = Form.serialize(form, true);
              var url = g_service_path + "/store/pay_using_credit_card_ajax";
              Yahoo_showLoading("Processing...");
              ajaxCall(url, {
                parameters: params,
                onComplete : Yahoo_hideLoading
              });
            }
          }
          catch(e){}
        },
        validateCreditCardInfo :  function(current_year, current_month){
          try{
            var credit_month = $('credit_month');
            var credit_year = $('credit_year');
            if ($("terms_condition").checked) {
              if ((parseInt(current_year) == parseInt(credit_year.value)) && (parseInt(credit_month.value) < parseInt(current_month))) {
                alert("The expiration date entered for the credit card is invalid. Please check the date and try again.");
                credit_month.focus();
                return false;
              }
              if (!StoreManager.alertFunction($("credit_card_number"), '10', 'Credit card number')) {
                return false;
              }
              if (!StoreManager.alertFunction($('security_code'), '3', 'Security code')) {
                return false;
              }
              return true;
            }else{
              alert("Please accept Terms and Condition...");
              return false;
            }
          }catch(e){alert("error validateCreditCardInfo "+e.message)}
        },

        /**
        * validate_email_signup
        * formObj - form object to validate the sign in form
        *
        */
        validate_email_signup: function (formObj, route, options){
          try {
            options = options || {}
            //All default values.
            var dOptions = {
                error_status: "error_status_signup",
                email_id_status_img: "email_id_status_img_su",
                sign_in_bt: "sign_up_bt",
                sign_in_loader: "sign_up_loader",
                urlPath: "/login/store_login"
            };

            options = YAHOO.lang.merge(dOptions, options);
            
            if (options.facebook_popup == 'true'){
              var fb_option = {
                urlPath: "/login/login_http"
              };
              options = YAHOO.lang.merge(options,fb_option);
            }

            var err_div = $(options.error_status);
            err_div.innerHTML = "";
            formObj.user_id.value = (new String(formObj.user_id.value)).strip();

            if (isBlank(formObj.user_id.value)) {
              err_div.innerHTML = ERR_MSG["EML_BLANK"];
              formObj.user_id.focus();
              return false;
            }
            else if (!validateSignInEmail(formObj.user_id, options.email_id_status_img)) {
              formObj.user_id.focus();
              err_div.innerHTML = "Please enter valid email id"
              return false;
            }
            else {
                
              try {
                $(options.sign_in_bt).style.display = "none";
                $(options.sign_in_loader).style.display = "";
              } catch(e){}
              
              new Ajax.Request(route + options.urlPath, {
                evalScripts: true,
                asynchronous: true,
                parameters: Form.serialize(formObj) + "&" + getLocationValues(),
                onSuccess : function () {
                    // you can remove the 'onbeforeunload' handler here
                    // which was there to tell user to save his/her unsaved
                    // designs, which one might create in not-logged-in view
                    if ( window.handleUnsavedDesign ) {
                        YAHOO.util.Event.removeListener( window, 'beforeunload', window.handleUnsavedDesign);
                    }
                },
                onComplete: function(){
                  $(options.sign_in_bt).style.display = "";
                  $(options.sign_in_loader).style.display = "none";
                }
              });
              return false;
            }
          }catch(e){}
          return false;
        },

        /**
    * validate_sign_in
    * formObj - form object to validate the sign in form
    *
    */
    validate_sign_in: function (formObj, route, options) {
      try {

          options = options ||
          {}
          //All default values.
          var dOptions = {
            error_status: "error_status",
            email_id_status_img: "email_id_status_img",
            pwd_status: "pwd_status",
            sign_in_bt: "sign_in_bt",
            sign_in_loader: "sign_in_loader",
            urlPath: "/login/store_login"
          };


          options = YAHOO.lang.merge(dOptions, options);
          if (options.facebook_popup == 'true'){
              var fb_option = {
                  urlPath: "/login/login_http"
              };
              options = YAHOO.lang.merge(options,fb_option);
          }
          var err_div = $(options.error_status);
          err_div.innerHTML = "";
          formObj.user_id.value = (new String(formObj.user_id.value)).strip();

          if (isBlank(formObj.user_id.value)) {
            err_div.innerHTML = ERR_MSG["EML_BLANK"];
            formObj.user_id.focus();
            return false;
          }
          else
            if (!validateSignInEmail(formObj.user_id, options.email_id_status_img)) {
              formObj.user_id.focus();
              return false;
            }
            else
              if ((formObj.password) && (!$('password').disabled) && (isBlank(formObj.password.value))) {
                err_div.innerHTML = ERR_MSG["PWD_BLANK"];
                formObj.password.focus();
                return false;
              }
              else
                if ((formObj.password) && (!$('password').disabled) && (!check_str_val(formObj.password.value, pwd_min_len, options.pwd_status, "Password", false))) {
                  showFalseStatus(ERR_MSG["PWD_MINLEN"], 'error_status');
                  formObj.password.focus();
                  return false;
                }
                else {
                    try {
                        $(options.sign_in_bt).style.display = "none";
                        $(options.sign_in_loader).style.display = "";
                    }
                    catch(e){}

                  new Ajax.Request(route + options.urlPath, {
                    evalScripts: true,
                    asynchronous: true,
                    parameters: Form.serialize(formObj) + "&" + getLocationValues(),
                    onSuccess : function () {
                        // you can remove the 'onbeforeunload' handler here
                        // which was there to tell user to save his/her unsaved
                        // designs, which one might create in not-logged-in view
                        if ( window.handleUnsavedDesign ) {
                            YAHOO.util.Event.removeListener( window, 'beforeunload', window.handleUnsavedDesign);
                        }
                    },
                    onComplete: function(){
                      $(options.sign_in_bt).style.display = "";
                      $(options.sign_in_loader).style.display = "none";
                    }
                  });
                  return false;
                }
         }
         catch(e){}
         return false;
      },

      /*
       * Method to hide/show country drop-down/input box based on country selection
      */
      toggleState: function(id) {
        try {

          if(id != 'billing_address_country') return 0;

          if($('billing_address_country').value == '1') {

            $('billing_address_state').hide();
            $('billing_address_state_sel').show();
            $('billing_address_state').value='';
            $('billing_address_state').value='';

          } else {

            $('billing_address_state_sel').hide();
            $('billing_address_state').show();
            $('billing_address_state').value='';
            $('billing_address_state_sel').value='';
            
          }
          
        } catch(e) {}
      },


      /**
      * validate_store_signup
      * formObj - form object to validate the sign in form        *
      */
        validate_store_signup: function (formObj, route, options){
          try {
            options = options || {}
            //All default values.
            var dOptions = {
                error_status: "error_status_signup",
                email_id_status_img: "email_id_status_img_su",
                sign_in_bt: "sign_up_bt",
                sign_in_loader: "sign_up_loader",
                urlPath: "/login/store_login"
            };

            options = YAHOO.lang.merge(dOptions, options);

            if (options.facebook_popup == 'true'){
              var fb_option = { urlPath: "/login/login_http" };
              options = YAHOO.lang.merge(options,fb_option);
            }

            if(!validate_full_name(formObj.full_name,'Full Name',true,'full_name_status')) {
              formObj.full_name.focus();
              return false;

            } else if(!check_email(Trim(formObj.user_id.value),'Email id','email_id_status_su',true)) {
              formObj.user_id.focus();
              return false;

            } else if (!check_pwd(formObj.password.value,6,'password_status','Password',true)) {
              formObj.password.focus();
              return false;

            } else {

              try {
                $(options.sign_in_bt).style.display = "none";
                $(options.sign_in_loader).style.display = "";
              } catch(e){}

              new Ajax.Request(route + options.urlPath, {
                evalScripts: true,
                asynchronous: true,
                parameters: Form.serialize(formObj) + "&" + getLocationValues(),
                onSuccess : function () {
                    // you can remove the 'onbeforeunload' handler here
                    // which was there to tell user to save his/her unsaved
                    // designs, which one might create in not-logged-in view
                    if ( window.handleUnsavedDesign ) {
                        YAHOO.util.Event.removeListener( window, 'beforeunload', window.handleUnsavedDesign);
                    }
                },
                onComplete: function(){
                  $(options.sign_in_bt).style.display = "";
                  $(options.sign_in_loader).style.display = "none";
                }
              });
              return false;
            }
          }catch(e){}
          return false;
        },

      /*
      * recalculateCart
      * Method to recalculate shipping cahrges, once user toggles b/w shipping types on checkout page
      * id : shipping type radio button element
      */
        recalculateCart : function(id) {
          try {

            var elem = $(id);
            //get code
            var code = elem.getAttribute('ship_code');
            
            Yahoo_showLoading('Updating cart...');
            var onComplete = function() {
              Yahoo_hideLoading();
            };

            var params = $H ({
                              code:code
                            });

            var url = g_service_path + "/dstore/update_cart_shipping_charges";

            ajaxCall(url,
                      {  parameters: params ,
                         onComplete: onComplete
                      }
                    );

          }catch(e) {}
        }
  }
}();



// creates the shipping rate table for HMG or where 'anchor id' will be available
var shipping_table_init = false;
YAHOO.util.Event.onDOMReady( function () {
    YAHOO.util.Event.onAvailable( "view-shipping-rates", function () {

        if (!shipping_table_init ) {

            try{
                var d = $('shipping-rate-dialog');

                if ( !d ) {
                    var d = document.createElement("div");
                    d.id = 'shipping-rate-dialog';
                    YAHOO.util.Dom.insertBefore( d, document.body.firstChild );
                }

                var dialog = new YAHOO.widget.Dialog( d, {
                    width : '400px',
                    constraintviewport: true,
                    modal : true,
                    visible : false
                } );

                // IE *** needs this thing
                if ( YAHOO.env.ua.ie && YAHOO.env.ua.ie <= 7 ) {
                    dialog.showEvent.subscribe( function () {
                        YAHOO.util.Dom.setStyle( 'hmg-shipping-table', 'display', 'block' );
                    } );
                }

                dialog.setHeader('Shipping Rates');
                dialog.setBody( $('hmg-shipping-table') );

                dialog.render();

                YAHOO.util.Event.on( this, "click", function ( e ) {
                    YAHOO.util.Event.stopEvent( e );
                    dialog.show();
                    dialog.center();
                } );

                shipping_table_init = true;

           }catch(e){}
        }

    } );
} );