﻿//<![CDATA[
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * URL QueryString Plugin
 *
 * Copyright (c) 2010
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.extend({
    getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name){
        return jQuery.getUrlVars()[name];
    }
});


//~INIT
var $j = jQuery.noConflict()

var gai = {};

$j(document).ready(function(){
    $j.validity.setup({
        // You may change the output mode with this property.
        outputMode: "label",
        
        // The this property is set to true, validity will scroll the browser viewport
        // so that the first error is visible when validation fails.
        scrollTo: false,

        // If a field name cannot be otherwise inferred, this will be used.
        defaultFieldName: "This field"
    });
});
   

//~DEBUGGER SCRIPT
var debugLineNumber = 1;
function $get(id) { return document.getElementById(id); }
function $getDebugLine() { 
    return "Line "+debugLineNumber+" : "; 
}
function $debug(value){
    //$get("debugger").innerHTML+=$getDebugLine()+value+"<br/>";debugLineNumber+=1;
    if($j.browser.mozilla){
        try { console.log(value); } catch (e) { }
        try { debug(value); } catch (e) { }
    }
    else {
        try { console.log(value); } catch (e) { }
        try { debug(value); } catch (e) { }
    }
}
function $debugtimer(start,value){
    if($j.browser.mozilla && start){
        try { console.time(value); } catch (e) { }
        try { debug(value); } catch (e) { }
    }
    else if($j.browser.mozilla){
        try { console.timeEnd(value); } catch (e) { }
        try { debug(value); } catch (e) { }
    }
    else {
        try { console.log(value); } catch (e) { }
        try { debug(value); } catch (e) { }
    }
}
//~END


function searchProduct() {$j(document).ready(function () {
    //    $debug("search filter : " + $j("#search-filter").val());
    //    var ghDialog = $j("<div style=\"text-align:left;height:50px;\"></div>")
    //	    .html("<span class=\"ui-icon ui-icon-alert\" style=\"float:left; margin:0 7px 50px 0;\"></span><p>Sorry for the inconvenience.<br/>Search under construction.</p>")
    //	    .dialog({
    //		    autoOpen: false,
    //		    height: 100,
    //		    width: 260,
    //		    resizable: false,
    //		    title: 'CRS Communication'		    
    //	});
    //	ghDialog.dialog('open');
    var temptext = $j("#searchtext").val();

    if (temptext == "Enter search word") { alert("Please enter a search word."); }
    else {
        location.href = "c71_searchresult.html#ecwid:keywords=" + $j("#searchtext").val() + " " + $j("#search-filter").val() + "&mode=search&offset=0&sort=relevance"
    }
});}


function mcValidateStep1() {
//$j(document).ready(function(){
    $j.validity.start();
    
        if( ( $j("#reg-step-1 input:radio:checked").val() != "Personal Account" ) && ( $j("#reg-step-1 input:radio:checked").val() != "Corporate Account" ) ) { $j("#ACCOUNTerror").require("Please select an Account Type."); }

    var result = $j.validity.end();
    
    if(result.valid){ $j("#mc-embedded-subscribe-form").removeClass("step1").addClass("step2"); }
    $debug("mcValidateStep1()");
//});
}

function mcValidateStep2() {
//$j(document).ready(function(){
    $j.validity.start();
        
        $j("#mce-EMAIL").require().match("email");
        $j("#mce-PASSWORD").require().match(/^(\w|\.|\+|\*|\?|\^|\$|\_|\-){1,15}$/, "Only alphanumeric & special character allowed.").minLength(7, "Must be more than 7 characters.").maxLength(15, "Your password is too long, max 15 characters.");
        $j("#mce-PASSWORD,#mce-REPASSWORD").require().equal("Passwords do not match.");

    var result = $j.validity.end();
    
    if(result.valid){ $j("#mc-embedded-subscribe-form").removeClass("step2").addClass("step3"); }
    $debug("mcValidateStep2()");
//});
}

function mcValidateStep3() {
//$j(document).ready(function(){
    $j.validity.start();
        
        $j("#mce-FNAME").require().match(/[a-zA-Z]/, "Only alpabets allowed.").minLength(3, "Must be more than 2 letters.").maxLength(50, "Your name is too long.");
        
        var mcDOB = $j("#mce-DOB-month").val()+"/"+$j("#mce-DOB-day").val()+"/"+$j("#mce-DOB-year").val() ;
        $j("#mce-DOB-Date").val(mcDOB).match("date","Invalid date, please check again.").range(new Date("12/31/1900"), new Date("12/31/2009"),"Date of birth must be between 31/12/1900 and 31/12/2009.");
        
        $j("#mce-MOBILE").require().match("integer").minLength(8, "Must be more than 8 digits.").maxLength(15, "Invalid phone number.");
        $j("#mce-PHONE").require().match("integer").minLength(8, "Must be more than 8 digits.").maxLength(15, "Invalid phone number.");

        if( $j("#mce-group-99:checked").val() != "Accept" ) { $j("#mce-group-00").require("You will need to accept the Terms & Conditions to proceed."); }

    var result = $j.validity.end();
    
    if(result.valid){ mcEcwidSync(); }
//});
}


function mcBackStep1() { $j("#mc-embedded-subscribe-form").removeClass("step2").addClass("step1"); }
function mcBackStep2() { $j("#mc-embedded-subscribe-form").removeClass("step3").addClass("step2"); }

var mceString="";
function mcEcwidSync(){
    
    $j(".ecwid-register-popup input[name='name']").val($j("#mce-FNAME").val());
    $j(".ecwid-register-popup input[name='email']").val($j("#mce-EMAIL").val());
    $j(".ecwid-register-popup input[name='password']").val($j("#mce-PASSWORD").val());
    
    $j(".ecwid-register-popup label.ecwid-fieldLabel").each(function(){
        if($j(this).text()=="Retype password") { 
            var tmpFor = $j(this).attr("for");
            $j("#"+tmpFor+" input.gwt-PasswordTextBox").val($j("#mce-REPASSWORD").val());
        }
        $debug("mcEcwidSync() : " +$j(this).text());
    });
    
    mcRegisterCreateString();
    ecwidCreateAccount();
}

function mcNewsletterSubscribe() {
    // Start Validation
    $j.validity.start();
        
        $j("#news-FNAME").require().match(/[a-zA-Z]{1,100}/, "Only alpabets allowed.").minLength(3, "Must be more than 2 letters.").maxLength(50, "Your name is too long.");
        $j("#news-EMAIL").require().match("email","Invalid email address.");

    var result = $j.validity.end();
    // End Validation

    if(result.valid){

        var mcEmail = $j("#news-EMAIL").val();
        var mcName = $j("#news-FNAME").val();
        
        //var regUrl = "http://us1.api.mailchimp.com/1.2/?method=listMemberInfo&apikey=bf8cb938db1cb6d22e8d43549714212d-us1&id=d07106e022&email_address="+mcEmail+"&output=xml";//
        var regUrl = "http://us1.api.mailchimp.com/1.2/?method=listSubscribe&apikey=bf8cb938db1cb6d22e8d43549714212d-us1&id=d07106e022&email_address="+mcEmail+"&merge_vars[FNAME]="+mcName+"&merge_vars[INTERESTS]=Products Updates and Promotions&update_existing=true&double_optin=true&output=json";//
        $debug(regUrl);

        $j("#news-SUBMIT").val("Please wait...").attr("onclick","");
        
        // Detect IE and use XDR
        if ($j.browser.msie && window.XDomainRequest) {
            // Use Microsoft XDR
            var xdr = new XDomainRequest();
            xdr.open("post", regUrl);
            xdr.onload = function() {
                // XDomainRequest doesn't provide responseXml, so if you need it:
                /*
                var dom = new ActiveXObject("Microsoft.XMLDOM");
                dom.async = true;
                dom.loadXML(xdr.responseText);
                */
                $j("#news-EMAIL").val("");$j("#news-FNAME").val("");$j("#news-SUBMIT").val("Subscribe").attr("onclick","mcNewsletterSubscribe()");
                alert("Application sent.\nThank you for subscribing.");
            };
            xdr.onerror = function(){
                $j("#news-EMAIL").val("");$j("#news-FNAME").val("");$j("#news-SUBMIT").val("Subscribe").attr("onclick","mcNewsletterSubscribe()");
                alert("Application sent.\nThank you for subscribing.");
            };
            xdr.ontimeout = mcXDRtimeout;
            xdr.timeout = 15000;
            xdr.send();
        } else {
            $j.get(regUrl, function(data){ 
                $debug( data ); 
                $j("#news-EMAIL").val("");
                $j("#news-FNAME").val("");
                $j("#news-SUBMIT").val("Subscribe").attr("onclick","mcNewsletterSubscribe()");
                alert("Application sent.\nThank you for subscribing.");
            });
        }
    }
}
function mcXDRerror()
{
    alert("Code:XDR03\nError occur, please try again.\nPlease contact the system administrator if the problem persist.");
}
function mcXDRtimeout()
{
    alert("Code:XDR09\nError occur, please try again.\nPlease contact the system administrator if the problem persist.");
}

function mcRegisterCreateString() {

    var mcAccount = "";
    var mcEmail = $j("#mce-EMAIL").val();
    var mcName = $j("#mce-FNAME").val();
    var mcDOB = $j("#mce-DOB-year").val()+"-"+$j("#mce-DOB-month").val()+"-"+$j("#mce-DOB-day").val() ;
    var mcMobile = $j("#mce-MOBILE").val();
    var mcPhone = $j("#mce-PHONE").val();
    var mcAddress = $j("#mce-ADDRESS").val();
    var mcInterest = "";
    
    if($j("#reg-step-1 input:radio:checked").length==1) { mcAccount = $j("#reg-step-1 input:radio:checked").val(); }
    
    if(($j("#mce-group-0:checked").length==1)&&($j("#mce-group-1:checked").length==1)) { mcInterest = $j("#mce-group-0:checked").val()+","+$j("#mce-group-1:checked").val(); }
    else if($j("#mce-group-0:checked").length==1) { mcInterest = $j("#mce-group-0:checked").val(); }
    else if($j("#mce-group-1:checked").length==1) { mcInterest = $j("#mce-group-1:checked").val(); }

    
    var regUrl = "http://us1.api.mailchimp.com/1.2/?method=listSubscribe&apikey=bf8cb938db1cb6d22e8d43549714212d-us1&id=d07106e022&email_address="+mcEmail+"&merge_vars[FNAME]="+mcName+"&merge_vars[LNAME]=&merge_vars[DOB]="+mcDOB+"&merge_vars[MOBILE]="+mcMobile+"&merge_vars[PHONE]="+mcPhone+"&merge_vars[ADDRESS]="+mcAddress+"&merge_vars[ACCOUNT]="+mcAccount+"&merge_vars[INTERESTS]="+mcInterest+"&double_optin=false&update_existing=true&output=json";//
    $debug(regUrl);
    
    mceString=regUrl;
}

function mcRegister() {
    $debug("mcRegister()");
    
    if ($j.browser.msie && window.XDomainRequest) {
        // Use Microsoft XDR
        var xdr = new XDomainRequest();
        xdr.open("post", mceString);
        xdr.onload = function(){
            alert("Success.\nWe will send you a confirmation email.");
        };
        xdr.onerror = function(){
            alert("Success.\nWe will send you a confirmation email.");
        };
        xdr.ontimeout = mcXDRtimeout;
        xdr.timeout = 15000;
        xdr.send();
    } else {
        $j.get(mceString, function(data){ 
            $debug( data ); 
            alert("Success.\nWe will send you a confirmation email."); 
            location.reload(true); 
        });
    }
}


function mcRegisterOpen() {
    $j("#mc-embedded-subscribe-form").addClass("step1");
    $j(".ecwid-register-popup .popupContent").append("<div id=\"ghRegister\"></div>");
    $j("#ghRegister").load("popup_register.html", function () { gai.autotextbox.init("#ghRegister") });
    //$j("#popup_wrapper").show();
}
function mcRegisterClose() {
    //$j("#popup_wrapper").hide();
    //$j("#mc-embedded-subscribe-form").removeClass("step1").removeClass("step2").removeClass("step3");
}

//]]>
