Modernizr.load([
    {
        test: Modernizr.backgroundsize,
        complete: function() {
            if(Modernizr.backgroundsize)
            {
            /* console.log('Backgroundsize is suppported'); */
            } else {
        /* console.log("Backgroundsize is not supported"); */
        }
        }
    }
    ]);
function getParameterByName(name)
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if(results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function updateTotals(totals)
{
    // totals is an array containing: subtotal, shippingOption, shippingCost, couponValue, tax, total, totalWithTax
    $.each(totals,function(i, val)
    {
        // i is the key, val is the value
        switch(i)
        {
            case 'shippingOption':
                $("#" + i ).html( val );
                break;
            case 'couponValue':
                $("#" + i ).html('- $' + val );
                break;
            case 'giftcardbalance':
                // handle giftcard if any
                if(totals['giftcardbalance'] > 0)
                {
                    var grandtotal = '0.00';
                    if (totals['totalWithTax'] - totals['giftcardbalance'] > 0)
                    {
                        grandtotal = totals['totalWithTax'] - totals['giftcardbalance'];
                    }
                    var balanceleft = totals['giftcardbalance'] - totals['totalWithTax'];
                    var balance = totals['giftcardbalance'];                    
                    $("#giftcardbalance").html( '$' + balance );
                    $("#grandtotal").html('$' + grandtotal );
                    $("#giftcardbalanceleft").html('You have $' + balanceleft + ' left on your gift card.' );

                    $("tr.grandtotal").show();
                    $("tr.giftcard").show();                    
                    $("tr.giftcardbalanceleft").show();

                }
                break;
            default:
                $("#" + i ).html('$' + val );
                break;
        }
        
    });    
}
 var worldRegions = ('country', 'region', 'region_id', {
        "US":{
            "1":{
                "code":"AL",
                "name":"Alabama"
            },
            "2":{
                "code":"AK",
                "name":"Alaska"
            },
            "3":{
                "code":"AS",
                "name":"American Samoa"
            },
            "4":{
                "code":"AZ",
                "name":"Arizona"
            },
            "5":{
                "code":"AR",
                "name":"Arkansas"
            },
            "6":{
                "code":"AF",
                "name":"Armed Forces Africa"
            },
            "7":{
                "code":"AA",
                "name":"Armed Forces Americas"
            },
            "8":{
                "code":"AC",
                "name":"Armed Forces Canada"
            },
            "9":{
                "code":"AE",
                "name":"Armed Forces Europe"
            },
            "10":{
                "code":"AM",
                "name":"Armed Forces Middle East"
            },
            "11":{
                "code":"AP",
                "name":"Armed Forces Pacific"
            },
            "12":{
                "code":"CA",
                "name":"California"
            },
            "13":{
                "code":"CO",
                "name":"Colorado"
            },
            "14":{
                "code":"CT",
                "name":"Connecticut"
            },
            "15":{
                "code":"DE",
                "name":"Delaware"
            },
            "16":{
                "code":"DC",
                "name":"District of Columbia"
            },
            "17":{
                "code":"FM",
                "name":"Federated States Of Micronesia"
            },
            "18":{
                "code":"FL",
                "name":"Florida"
            },
            "19":{
                "code":"GA",
                "name":"Georgia"
            },
            "20":{
                "code":"GU",
                "name":"Guam"
            },
            "21":{
                "code":"HI",
                "name":"Hawaii"
            },
            "22":{
                "code":"ID",
                "name":"Idaho"
            },
            "23":{
                "code":"IL",
                "name":"Illinois"
            },
            "24":{
                "code":"IN",
                "name":"Indiana"
            },
            "25":{
                "code":"IA",
                "name":"Iowa"
            },
            "26":{
                "code":"KS",
                "name":"Kansas"
            },
            "27":{
                "code":"KY",
                "name":"Kentucky"
            },
            "28":{
                "code":"LA",
                "name":"Louisiana"
            },
            "29":{
                "code":"ME",
                "name":"Maine"
            },
            "30":{
                "code":"MH",
                "name":"Marshall Islands"
            },
            "31":{
                "code":"MD",
                "name":"Maryland"
            },
            "32":{
                "code":"MA",
                "name":"Massachusetts"
            },
            "33":{
                "code":"MI",
                "name":"Michigan"
            },
            "34":{
                "code":"MN",
                "name":"Minnesota"
            },
            "35":{
                "code":"MS",
                "name":"Mississippi"
            },
            "36":{
                "code":"MO",
                "name":"Missouri"
            },
            "37":{
                "code":"MT",
                "name":"Montana"
            },
            "38":{
                "code":"NE",
                "name":"Nebraska"
            },
            "39":{
                "code":"NV",
                "name":"Nevada"
            },
            "40":{
                "code":"NH",
                "name":"New Hampshire"
            },
            "41":{
                "code":"NJ",
                "name":"New Jersey"
            },
            "42":{
                "code":"NM",
                "name":"New Mexico"
            },
            "43":{
                "code":"NY",
                "name":"New York"
            },
            "44":{
                "code":"NC",
                "name":"North Carolina"
            },
            "45":{
                "code":"ND",
                "name":"North Dakota"
            },
            "46":{
                "code":"MP",
                "name":"Northern Mariana Islands"
            },
            "47":{
                "code":"OH",
                "name":"Ohio"
            },
            "48":{
                "code":"OK",
                "name":"Oklahoma"
            },
            "49":{
                "code":"OR",
                "name":"Oregon"
            },
            "50":{
                "code":"PW",
                "name":"Palau"
            },
            "51":{
                "code":"PA",
                "name":"Pennsylvania"
            },
            "52":{
                "code":"PR",
                "name":"Puerto Rico"
            },
            "53":{
                "code":"RI",
                "name":"Rhode Island"
            },
            "54":{
                "code":"SC",
                "name":"South Carolina"
            },
            "55":{
                "code":"SD",
                "name":"South Dakota"
            },
            "56":{
                "code":"TN",
                "name":"Tennessee"
            },
            "57":{
                "code":"TX",
                "name":"Texas"
            },
            "58":{
                "code":"UT",
                "name":"Utah"
            },
            "59":{
                "code":"VT",
                "name":"Vermont"
            },
            "60":{
                "code":"VI",
                "name":"Virgin Islands"
            },
            "61":{
                "code":"VA",
                "name":"Virginia"
            },
            "62":{
                "code":"WA",
                "name":"Washington"
            },
            "63":{
                "code":"WV",
                "name":"West Virginia"
            },
            "64":{
                "code":"WI",
                "name":"Wisconsin"
            },
            "65":{
                "code":"WY",
                "name":"Wyoming"
            }
        },
        "CA":{
            "66":{
                "code":"AB",
                "name":"Alberta"
            },
            "67":{
                "code":"BC",
                "name":"British Columbia"
            },
            "68":{
                "code":"MB",
                "name":"Manitoba"
            },
            "69":{
                "code":"NL",
                "name":"Newfoundland and Labrador"
            },
            "70":{
                "code":"NB",
                "name":"New Brunswick"
            },
            "71":{
                "code":"NS",
                "name":"Nova Scotia"
            },
            "72":{
                "code":"NT",
                "name":"Northwest Territories"
            },
            "73":{
                "code":"NU",
                "name":"Nunavut"
            },
            "74":{
                "code":"ON",
                "name":"Ontario"
            },
            "75":{
                "code":"PE",
                "name":"Prince Edward Island"
            },
            "76":{
                "code":"QC",
                "name":"Quebec"
            },
            "77":{
                "code":"SK",
                "name":"Saskatchewan"
            },
            "78":{
                "code":"YT",
                "name":"Yukon Territory"
            }
        },
        "DE":{
            "79":{
                "code":"NDS",
                "name":"Niedersachsen"
            },
            "80":{
                "code":"BAW",
                "name":"Baden-W\u00fcrttemberg"
            },
            "81":{
                "code":"BAY",
                "name":"Bayern"
            },
            "82":{
                "code":"BER",
                "name":"Berlin"
            },
            "83":{
                "code":"BRG",
                "name":"Brandenburg"
            },
            "84":{
                "code":"BRE",
                "name":"Bremen"
            },
            "85":{
                "code":"HAM",
                "name":"Hamburg"
            },
            "86":{
                "code":"HES",
                "name":"Hessen"
            },
            "87":{
                "code":"MEC",
                "name":"Mecklenburg-Vorpommern"
            },
            "88":{
                "code":"NRW",
                "name":"Nordrhein-Westfalen"
            },
            "89":{
                "code":"RHE",
                "name":"Rheinland-Pfalz"
            },
            "90":{
                "code":"SAR",
                "name":"Saarland"
            },
            "91":{
                "code":"SAS",
                "name":"Sachsen"
            },
            "92":{
                "code":"SAC",
                "name":"Sachsen-Anhalt"
            },
            "93":{
                "code":"SCN",
                "name":"Schleswig-Holstein"
            },
            "94":{
                "code":"THE",
                "name":"Th\u00fcringen"
            }
        },
        "AT":{
            "95":{
                "code":"WI",
                "name":"Wien"
            },
            "96":{
                "code":"NO",
                "name":"Nieder\u00f6sterreich"
            },
            "97":{
                "code":"OO",
                "name":"Ober\u00f6sterreich"
            },
            "98":{
                "code":"SB",
                "name":"Salzburg"
            },
            "99":{
                "code":"KN",
                "name":"K\u00e4rnten"
            },
            "100":{
                "code":"ST",
                "name":"Steiermark"
            },
            "101":{
                "code":"TI",
                "name":"Tirol"
            },
            "102":{
                "code":"BL",
                "name":"Burgenland"
            },
            "103":{
                "code":"VB",
                "name":"Voralberg"
            }
        },
        "CH":{
            "104":{
                "code":"AG",
                "name":"Aargau"
            },
            "105":{
                "code":"AI",
                "name":"Appenzell Innerrhoden"
            },
            "106":{
                "code":"AR",
                "name":"Appenzell Ausserrhoden"
            },
            "107":{
                "code":"BE",
                "name":"Bern"
            },
            "108":{
                "code":"BL",
                "name":"Basel-Landschaft"
            },
            "109":{
                "code":"BS",
                "name":"Basel-Stadt"
            },
            "110":{
                "code":"FR",
                "name":"Freiburg"
            },
            "111":{
                "code":"GE",
                "name":"Genf"
            },
            "112":{
                "code":"GL",
                "name":"Glarus"
            },
            "113":{
                "code":"GR",
                "name":"Graub\u00fcnden"
            },
            "114":{
                "code":"JU",
                "name":"Jura"
            },
            "115":{
                "code":"LU",
                "name":"Luzern"
            },
            "116":{
                "code":"NE",
                "name":"Neuenburg"
            },
            "117":{
                "code":"NW",
                "name":"Nidwalden"
            },
            "118":{
                "code":"OW",
                "name":"Obwalden"
            },
            "119":{
                "code":"SG",
                "name":"St. Gallen"
            },
            "120":{
                "code":"SH",
                "name":"Schaffhausen"
            },
            "121":{
                "code":"SO",
                "name":"Solothurn"
            },
            "122":{
                "code":"SZ",
                "name":"Schwyz"
            },
            "123":{
                "code":"TG",
                "name":"Thurgau"
            },
            "124":{
                "code":"TI",
                "name":"Tessin"
            },
            "125":{
                "code":"UR",
                "name":"Uri"
            },
            "126":{
                "code":"VD",
                "name":"Waadt"
            },
            "127":{
                "code":"VS",
                "name":"Wallis"
            },
            "128":{
                "code":"ZG",
                "name":"Zug"
            },
            "129":{
                "code":"ZH",
                "name":"Z\u00fcrich"
            }
        },
        "ES":{
            "130":{
                "code":"A Coru\u0441a",
                "name":"A Coru\u00f1a"
            },
            "131":{
                "code":"Alava",
                "name":"Alava"
            },
            "132":{
                "code":"Albacete",
                "name":"Albacete"
            },
            "133":{
                "code":"Alicante",
                "name":"Alicante"
            },
            "134":{
                "code":"Almeria",
                "name":"Almeria"
            },
            "135":{
                "code":"Asturias",
                "name":"Asturias"
            },
            "136":{
                "code":"Avila",
                "name":"Avila"
            },
            "137":{
                "code":"Badajoz",
                "name":"Badajoz"
            },
            "138":{
                "code":"Baleares",
                "name":"Baleares"
            },
            "139":{
                "code":"Barcelona",
                "name":"Barcelona"
            },
            "140":{
                "code":"Burgos",
                "name":"Burgos"
            },
            "141":{
                "code":"Caceres",
                "name":"Caceres"
            },
            "142":{
                "code":"Cadiz",
                "name":"Cadiz"
            },
            "143":{
                "code":"Cantabria",
                "name":"Cantabria"
            },
            "144":{
                "code":"Castellon",
                "name":"Castellon"
            },
            "145":{
                "code":"Ceuta",
                "name":"Ceuta"
            },
            "146":{
                "code":"Ciudad Real",
                "name":"Ciudad Real"
            },
            "147":{
                "code":"Cordoba",
                "name":"Cordoba"
            },
            "148":{
                "code":"Cuenca",
                "name":"Cuenca"
            },
            "149":{
                "code":"Girona",
                "name":"Girona"
            },
            "150":{
                "code":"Granada",
                "name":"Granada"
            },
            "151":{
                "code":"Guadalajara",
                "name":"Guadalajara"
            },
            "152":{
                "code":"Guipuzcoa",
                "name":"Guipuzcoa"
            },
            "153":{
                "code":"Huelva",
                "name":"Huelva"
            },
            "154":{
                "code":"Huesca",
                "name":"Huesca"
            },
            "155":{
                "code":"Jaen",
                "name":"Jaen"
            },
            "156":{
                "code":"La Rioja",
                "name":"La Rioja"
            },
            "157":{
                "code":"Las Palmas",
                "name":"Las Palmas"
            },
            "158":{
                "code":"Leon",
                "name":"Leon"
            },
            "159":{
                "code":"Lleida",
                "name":"Lleida"
            },
            "160":{
                "code":"Lugo",
                "name":"Lugo"
            },
            "161":{
                "code":"Madrid",
                "name":"Madrid"
            },
            "162":{
                "code":"Malaga",
                "name":"Malaga"
            },
            "163":{
                "code":"Melilla",
                "name":"Melilla"
            },
            "164":{
                "code":"Murcia",
                "name":"Murcia"
            },
            "165":{
                "code":"Navarra",
                "name":"Navarra"
            },
            "166":{
                "code":"Ourense",
                "name":"Ourense"
            },
            "167":{
                "code":"Palencia",
                "name":"Palencia"
            },
            "168":{
                "code":"Pontevedra",
                "name":"Pontevedra"
            },
            "169":{
                "code":"Salamanca",
                "name":"Salamanca"
            },
            "170":{
                "code":"Santa Cruz de Tenerife",
                "name":"Santa Cruz de Tenerife"
            },
            "171":{
                "code":"Segovia",
                "name":"Segovia"
            },
            "172":{
                "code":"Sevilla",
                "name":"Sevilla"
            },
            "173":{
                "code":"Soria",
                "name":"Soria"
            },
            "174":{
                "code":"Tarragona",
                "name":"Tarragona"
            },
            "175":{
                "code":"Teruel",
                "name":"Teruel"
            },
            "176":{
                "code":"Toledo",
                "name":"Toledo"
            },
            "177":{
                "code":"Valencia",
                "name":"Valencia"
            },
            "178":{
                "code":"Valladolid",
                "name":"Valladolid"
            },
            "179":{
                "code":"Vizcaya",
                "name":"Vizcaya"
            },
            "180":{
                "code":"Zamora",
                "name":"Zamora"
            },
            "181":{
                "code":"Zaragoza",
                "name":"Zaragoza"
            }
        },
        "FR":{
            "182":{
                "code":"01",
                "name":"Ain"
            },
            "183":{
                "code":"02",
                "name":"Aisne"
            },
            "184":{
                "code":"03",
                "name":"Allier"
            },
            "185":{
                "code":"04",
                "name":"Alpes-de-Haute-Provence"
            },
            "186":{
                "code":"05",
                "name":"Hautes-Alpes"
            },
            "187":{
                "code":"06",
                "name":"Alpes-Maritimes"
            },
            "188":{
                "code":"07",
                "name":"Ard\u00e8che"
            },
            "189":{
                "code":"08",
                "name":"Ardennes"
            },
            "190":{
                "code":"09",
                "name":"Ari\u00e8ge"
            },
            "191":{
                "code":"10",
                "name":"Aube"
            },
            "192":{
                "code":"11",
                "name":"Aude"
            },
            "193":{
                "code":"12",
                "name":"Aveyron"
            },
            "194":{
                "code":"13",
                "name":"Bouches-du-Rh\u00f4ne"
            },
            "195":{
                "code":"14",
                "name":"Calvados"
            },
            "196":{
                "code":"15",
                "name":"Cantal"
            },
            "197":{
                "code":"16",
                "name":"Charente"
            },
            "198":{
                "code":"17",
                "name":"Charente-Maritime"
            },
            "199":{
                "code":"18",
                "name":"Cher"
            },
            "200":{
                "code":"19",
                "name":"Corr\u00e8ze"
            },
            "201":{
                "code":"2A",
                "name":"Corse-du-Sud"
            },
            "202":{
                "code":"2B",
                "name":"Haute-Corse"
            },
            "203":{
                "code":"21",
                "name":"C\u00f4te-d'Or"
            },
            "204":{
                "code":"22",
                "name":"C\u00f4tes-d'Armor"
            },
            "205":{
                "code":"23",
                "name":"Creuse"
            },
            "206":{
                "code":"24",
                "name":"Dordogne"
            },
            "207":{
                "code":"25",
                "name":"Doubs"
            },
            "208":{
                "code":"26",
                "name":"Dr\u00f4me"
            },
            "209":{
                "code":"27",
                "name":"Eure"
            },
            "210":{
                "code":"28",
                "name":"Eure-et-Loir"
            },
            "211":{
                "code":"29",
                "name":"Finist\u00e8re"
            },
            "212":{
                "code":"30",
                "name":"Gard"
            },
            "213":{
                "code":"31",
                "name":"Haute-Garonne"
            },
            "214":{
                "code":"32",
                "name":"Gers"
            },
            "215":{
                "code":"33",
                "name":"Gironde"
            },
            "216":{
                "code":"34",
                "name":"H\u00e9rault"
            },
            "217":{
                "code":"35",
                "name":"Ille-et-Vilaine"
            },
            "218":{
                "code":"36",
                "name":"Indre"
            },
            "219":{
                "code":"37",
                "name":"Indre-et-Loire"
            },
            "220":{
                "code":"38",
                "name":"Is\u00e8re"
            },
            "221":{
                "code":"39",
                "name":"Jura"
            },
            "222":{
                "code":"40",
                "name":"Landes"
            },
            "223":{
                "code":"41",
                "name":"Loir-et-Cher"
            },
            "224":{
                "code":"42",
                "name":"Loire"
            },
            "225":{
                "code":"43",
                "name":"Haute-Loire"
            },
            "226":{
                "code":"44",
                "name":"Loire-Atlantique"
            },
            "227":{
                "code":"45",
                "name":"Loiret"
            },
            "228":{
                "code":"46",
                "name":"Lot"
            },
            "229":{
                "code":"47",
                "name":"Lot-et-Garonne"
            },
            "230":{
                "code":"48",
                "name":"Loz\u00e8re"
            },
            "231":{
                "code":"49",
                "name":"Maine-et-Loire"
            },
            "232":{
                "code":"50",
                "name":"Manche"
            },
            "233":{
                "code":"51",
                "name":"Marne"
            },
            "234":{
                "code":"52",
                "name":"Haute-Marne"
            },
            "235":{
                "code":"53",
                "name":"Mayenne"
            },
            "236":{
                "code":"54",
                "name":"Meurthe-et-Moselle"
            },
            "237":{
                "code":"55",
                "name":"Meuse"
            },
            "238":{
                "code":"56",
                "name":"Morbihan"
            },
            "239":{
                "code":"57",
                "name":"Moselle"
            },
            "240":{
                "code":"58",
                "name":"Ni\u00e8vre"
            },
            "241":{
                "code":"59",
                "name":"Nord"
            },
            "242":{
                "code":"60",
                "name":"Oise"
            },
            "243":{
                "code":"61",
                "name":"Orne"
            },
            "244":{
                "code":"62",
                "name":"Pas-de-Calais"
            },
            "245":{
                "code":"63",
                "name":"Puy-de-D\u00f4me"
            },
            "246":{
                "code":"64",
                "name":"Pyr\u00e9n\u00e9es-Atlantiques"
            },
            "247":{
                "code":"65",
                "name":"Hautes-Pyr\u00e9n\u00e9es"
            },
            "248":{
                "code":"66",
                "name":"Pyr\u00e9n\u00e9es-Orientales"
            },
            "249":{
                "code":"67",
                "name":"Bas-Rhin"
            },
            "250":{
                "code":"68",
                "name":"Haut-Rhin"
            },
            "251":{
                "code":"69",
                "name":"Rh\u00f4ne"
            },
            "252":{
                "code":"70",
                "name":"Haute-Sa\u00f4ne"
            },
            "253":{
                "code":"71",
                "name":"Sa\u00f4ne-et-Loire"
            },
            "254":{
                "code":"72",
                "name":"Sarthe"
            },
            "255":{
                "code":"73",
                "name":"Savoie"
            },
            "256":{
                "code":"74",
                "name":"Haute-Savoie"
            },
            "257":{
                "code":"75",
                "name":"Paris"
            },
            "258":{
                "code":"76",
                "name":"Seine-Maritime"
            },
            "259":{
                "code":"77",
                "name":"Seine-et-Marne"
            },
            "260":{
                "code":"78",
                "name":"Yvelines"
            },
            "261":{
                "code":"79",
                "name":"Deux-S\u00e8vres"
            },
            "262":{
                "code":"80",
                "name":"Somme"
            },
            "263":{
                "code":"81",
                "name":"Tarn"
            },
            "264":{
                "code":"82",
                "name":"Tarn-et-Garonne"
            },
            "265":{
                "code":"83",
                "name":"Var"
            },
            "266":{
                "code":"84",
                "name":"Vaucluse"
            },
            "267":{
                "code":"85",
                "name":"Vend\u00e9e"
            },
            "268":{
                "code":"86",
                "name":"Vienne"
            },
            "269":{
                "code":"87",
                "name":"Haute-Vienne"
            },
            "270":{
                "code":"88",
                "name":"Vosges"
            },
            "271":{
                "code":"89",
                "name":"Yonne"
            },
            "272":{
                "code":"90",
                "name":"Territoire-de-Belfort"
            },
            "273":{
                "code":"91",
                "name":"Essonne"
            },
            "274":{
                "code":"92",
                "name":"Hauts-de-Seine"
            },
            "275":{
                "code":"93",
                "name":"Seine-Saint-Denis"
            },
            "276":{
                "code":"94",
                "name":"Val-de-Marne"
            },
            "277":{
                "code":"95",
                "name":"Val-d'Oise"
            }
        },
        "RO":{
            "278":{
                "code":"AB",
                "name":"Alba"
            },
            "279":{
                "code":"AR",
                "name":"Arad"
            },
            "280":{
                "code":"AG",
                "name":"Arge\u015f"
            },
            "281":{
                "code":"BC",
                "name":"Bac\u0103u"
            },
            "282":{
                "code":"BH",
                "name":"Bihor"
            },
            "283":{
                "code":"BN",
                "name":"Bistri\u0163a-N\u0103s\u0103ud"
            },
            "284":{
                "code":"BT",
                "name":"Boto\u015fani"
            },
            "285":{
                "code":"BV",
                "name":"Bra\u015fov"
            },
            "286":{
                "code":"BR",
                "name":"Br\u0103ila"
            },
            "287":{
                "code":"B",
                "name":"Bucure\u015fti"
            },
            "288":{
                "code":"BZ",
                "name":"Buz\u0103u"
            },
            "289":{
                "code":"CS",
                "name":"Cara\u015f-Severin"
            },
            "290":{
                "code":"CL",
                "name":"C\u0103l\u0103ra\u015fi"
            },
            "291":{
                "code":"CJ",
                "name":"Cluj"
            },
            "292":{
                "code":"CT",
                "name":"Constan\u0163a"
            },
            "293":{
                "code":"CV",
                "name":"Covasna"
            },
            "294":{
                "code":"DB",
                "name":"D\u00e2mbovi\u0163a"
            },
            "295":{
                "code":"DJ",
                "name":"Dolj"
            },
            "296":{
                "code":"GL",
                "name":"Gala\u0163i"
            },
            "297":{
                "code":"GR",
                "name":"Giurgiu"
            },
            "298":{
                "code":"GJ",
                "name":"Gorj"
            },
            "299":{
                "code":"HR",
                "name":"Harghita"
            },
            "300":{
                "code":"HD",
                "name":"Hunedoara"
            },
            "301":{
                "code":"IL",
                "name":"Ialomi\u0163a"
            },
            "302":{
                "code":"IS",
                "name":"Ia\u015fi"
            },
            "303":{
                "code":"IF",
                "name":"Ilfov"
            },
            "304":{
                "code":"MM",
                "name":"Maramure\u015f"
            },
            "305":{
                "code":"MH",
                "name":"Mehedin\u0163i"
            },
            "306":{
                "code":"MS",
                "name":"Mure\u015f"
            },
            "307":{
                "code":"NT",
                "name":"Neam\u0163"
            },
            "308":{
                "code":"OT",
                "name":"Olt"
            },
            "309":{
                "code":"PH",
                "name":"Prahova"
            },
            "310":{
                "code":"SM",
                "name":"Satu-Mare"
            },
            "311":{
                "code":"SJ",
                "name":"S\u0103laj"
            },
            "312":{
                "code":"SB",
                "name":"Sibiu"
            },
            "313":{
                "code":"SV",
                "name":"Suceava"
            },
            "314":{
                "code":"TR",
                "name":"Teleorman"
            },
            "315":{
                "code":"TM",
                "name":"Timi\u015f"
            },
            "316":{
                "code":"TL",
                "name":"Tulcea"
            },
            "317":{
                "code":"VS",
                "name":"Vaslui"
            },
            "318":{
                "code":"VL",
                "name":"V\u00e2lcea"
            },
            "319":{
                "code":"VN",
                "name":"Vrancea"
            }
        }
    });
var activeTab = "Information1";
function swapIt(o) {    
    o.blur(); // hide the tab content
    if(o.className == "current") return false; // return false if user clicked current tab
          
    var newTab = o.title;          
    // update tabs
    var list = document.getElementById("Navigation").getElementsByTagName("a");
    for (var i = 0; i < list.length; i++) {
        if (list[i].className == "current") {
            list[i].className = "";                  
        }
        if (list[i].title == o.title) o.className = "current";
    }
    $("#" + activeTab).hide();
    $("#" + newTab).fadeIn();
    activeTab = newTab;
    $("#" + activeTab).tinyscrollbar_update();
}
function updateCartTable()
{
    var ids = [];
    
    if($("#cart_table").length > 0)
    {
        $("#cart_table tr.tr_cart_data :nth-child(5)").each(function(){
            var target = $(this).children('input');
            var qty = $(target).attr('value');
            var id  = $(target).attr('id');
            var price = $(this).parent().find('.price').html();
            // console.log("qty: " + qty + "price: " + price);
            ids.push( id + ':' + qty);
            if(qty == 0){
                $(this).parent().fadeOut(1000,function(){
                    $(this).remove();
                    if($("#cart_table tr.tr_cart_data").length == 0) {
                        $("#cart-content").css({
                            'height':'300px'
                        });
                        $("#cart-options").fadeOut();
                        $("#cart_table").fadeOut(1000,function(){
                            $(this).remove();
                            $("h1.moonrise_red").after('<p><span>Your Shopping Cart is empty</span></p>');
                            $("#viewcart_lnk").html('VIEW CART / CHECKOUT');
                        });
                    }
                });
            } else {
                // quantity > 0 -- update product total
                $(this).parent().find('.productTotal').html("$" + (price * qty).toFixed(2));
            }
        });
            
        return ids;
    }
}

$(document).ready(function(){
    

    /* DEFINING VARIABLE */
    
    // detect touch devices to turn off any mouseover only functions
    window.is_touch_device = (/iPhone|iPod|iPad/i).test(navigator.userAgent);
    var istouch = (window.is_touch_device)?'true':'false';    

    var ajax_uri = '/index.php/ajax';
    var ajax_checkout_uri = '/index.php/checkout/ajax'; 
 
    /* CATEGORY PAGE */
    if($(".float img").length > 0 && !window.is_touch_device){
        $(".float img").each(function(){

            var thumb = $(this);
            var full = thumb.attr('rel');

            var content = $('<img />', {
                src: full
            });

            // Create tooltip
            $(this).qtip({
                content: {
                    text: content,
                    title: {
                        text: thumb.attr('alt')
                    }
                },
                position: {
                    at: "left center",
                    my: "right center"
                },
                hide: {
                    fixed: true
                },
                style: {
                    classes: "ui-tooltip-tipsy ui-tooltip-flickr",                 
                  
                  background: '#A2D959',
                  color: 'black',
                  textAlign: 'center',
                  border: {
                     width: 7,
                     radius: 5,
                     color: '#A2D959'
                  }
                }
            })
        })
    }
 

    tinyMCE.init({
        theme: 'advanced',
        mode: 'exact',
        elements: 'tinymce',
        width: '450px',
        height: '200px'
    });
    
    /* CHECKOUT */
    
   
    // shipping
    var country_id = $("#country_id");
    var region_id  = $("#region_id");
    // billing
    var b_country_id = $("#b_country_id");
    var b_region_id  = $("#b_region_id");        

    var addressFields = ['firstName', 'lastName', 'email', 'company','street','street2','city','zip','region','country'];

    var myForm = $("#frm_login");        
    // enable the accordion
    var wizard = $("#accordion").accordion({
        header: 'h2',
        autoHeight: false,
        event: false
    });

    var selectedTab = 0;
    var selectedPage = $("#accordion").attr('rel');  
    
    setPage(selectedPage, selectedTab); 

    function setPage(newPage, newTab){        
        selectedTab = newTab;
        var page = parseInt(newPage);
        var tab = parseInt(newTab);        
        switch(page){
            case 0:
                break;
            case 1:
                $("#lnk_edit_shipping").show();
                break;
            case 2:
                $("#lnk_edit_billing").show();
                $("#lnk_edit_shipping").show();
                break;
            default:
                break;
        }
            
        $("#accordion").accordion("activate", page);
        
        $("#tabs").tabs({ 
            selected: tab,
            fx: {
                opacity: 'toggle'
            },
            select: function(event, ui){
            // $("#accordion").accordion("resize");
            }
        });
    }
    
    $("#giftwrap").change(function(){
        // $("#btn_pay_now").hide();
        // $("#btn_update_order").show();
        var giftwrap = $(this).attr('checked');
        var xhr = $.ajax({
            url:    ajax_checkout_uri,
            method: 'GET',
            data:   'req=giftwrap&wrap=' + giftwrap,
            success: function(obj){
                data = eval("(" + obj + ")");
                if(data['result']=='success')
                {
                    updateTotals(data['totals']);
                }
                if(giftwrap == 'checked')
                {
                    $("#tr_giftwrap").show();
                }
                else
                {
                    $("#tr_giftwrap").hide();
                }
            }
        })
    })
        
    $("#btn_lookup_giftcertificate").click(function(event){
        event.preventDefault();
        var giftcertificatecode  = $("#giftcertificatecode").attr('value');
        var giftcertificateemail = $("#giftcertificateemail").attr('value');
        var xhr = $.ajax({
            url: ajax_checkout_uri,
            method: 'GET',
            data: 'req=lookupGiftCard&giftcardcode=' + giftcertificatecode + '&email=' + giftcertificateemail,
            success: function(obj){
                data = eval('(' + obj + ')');
                console.log(data);
                if(data['result']=='success')
                {
                    $("#giftcardvalue").html('Available Balance: <span style="font-size:1.4em;">$' + data['balance'] + '</span>');
                    if(data['balance']>0){
                        $("#btn_lookup_giftcertificate").hide();
                        $("#gc_email").show();
                        $("#btn_redeem_giftcertificate").show();
                    }
                }
                else
                {
                    $("#giftcarderror").html(data['errormessage']);
                }
                    
            }
        })
    });
        
    $("#btn_redeem_giftcertificate").click(function(event)
    {            
        event.preventDefault();
        var giftcertificatecode = $("#giftcertificatecode").attr('value');
        var giftcertificateemail = $("#giftcertificateemail").attr('value');
        var email = $("#gc_email_address");
        email.removeClass('error');
        var regexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i ;
        if(regexp.test(email.val()))
        {
            var xhr = $.ajax({
                url: ajax_checkout_uri,
                method: 'GET',
                data: 'req=setPaymentMethod&method=giftcard&giftcardcode=' + giftcertificatecode + '&email=' + email.val(),
                success: function(obj){
                    data = eval('(' + obj + ')');
                    console.log(data);
                    if(data['result']=='success')
                    {
                        $("#gc_billing_info").show();
                        $("#gc_shipping_info").show();                        

                        updateTotals(data['totals']);

                        if(data['totals']['totalWithTax'] - data['totals']['giftcardbalance'] > 0)
                        {
                            $("#billingnotice").html('There is $' + (data['totals']['totalWithTax'] - data['totals']['giftcardbalance']).toFixed(2) + ' left, please select an additional payment option.').show();
                        }
                        else
                        {
                            $("#billing_email").html(email.val());
                            setPage(2, selectedTab);
                        }
                    }
                    else
                    {
                        $("#giftcarderror").html(data['errormessage']);
                    }

                }
            });
        }
        else
        {
            email.addClass('error');
        }
    });
        
    $("#btn_billing_cod").click(function(event){
        event.preventDefault();        
        var email = $("#cod_email_billing");
        email.removeClass('error');
        var regexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i ;
        if(regexp.test(email.val()))
        {
            var xhr = $.ajax({
                url:    ajax_checkout_uri,
                method: 'GET',
                data:   'req=setPaymentMethod&method=cod&email=' + email.val(),
                success: function(obj){
                    data = eval('(' + obj + ')');
                    if(data['result']=='success')
                    {
                        updateTotals(data['totals']);
                        $("#billing_email").html(email.val());
                        setPage(2, selectedTab);
                        $(".cod").show();
                    }
                }
            });
        }
        else
        {
            email.addClass('error');
        }
    })
        
    $("#lnk_same_as_shipping").click(function(){
        $.each(addressFields,function(i,val){
            $("#b_"+ val).attr('value',$("#"+val).attr('value'));
                
        })
        $("#b_region_id").val($("#region_id").val());
    })
        
    $("#lnk_edit_shipping_option").click(function(event){
        event.preventDefault();
        // hide standard shipping
            
        // setup shipping vars
        var country = $("option:selected",country_id).val();
        
        var region = $("option:selected",region_id).val();
        
        var zip = $("#zip").val();
        // if the customer hasn't provided zip and state, highlight those fields
        if(country == 'US' && region == '')
        {
            (region == '')?region_id.addClass('error'):'';            
        }
        else
        {
            // make the call & get the shipping quote
            $.ajax({
                url: ajax_checkout_uri,
                method: 'GET',
                data: 'req=getShippingQuote&zip=' + zip + '&country=' + country + '&region=' + region,
                success: function(obj) {
                    data = eval('(' + obj + ')');
                    // console.log(data);
                    $("tr.standardshipping").hide();
                    var html = '<table>';
                    $.each(data, function(i,val)
                    {
                        // i is index (e.g. Special Offer / UPS / totals)
                        // filter out the totals information, don't need that now
                        if(i != 'totals')
                        {
                            html += '<tr valign="top"><td><label class="shippingoptionheader">' + i + '</label></td><td><table width="600">';
                            $.each(val,function(j,value)
                            {
                                // j holds key e.g. UPS Ground, 3 Day Select etc.
                                // value hold the price
                                html += '<tr valign="top"><td width="175"><input type="radio"';
                                html += 'rel="' + value['max'] + '"';
                                html += 'value="' + value['price'] + '" name="order[shipping][shippingOption]" id="';
                                html += j + '"><label class="shippingoption">'+ j + '</label></td><td><span class="shippingoptionprice">$';
                                html += value['price'].toFixed(2);
                                html += '</span></td><td><span style="font-style:italic">estimated delivery on or before ' + value['delivery'];
                                html += '</span></td></tr>';
                            });
                            html += '</tr></table>';
                        }
                    })
                    html += '</table>';
                    // append to  tr.chooseshippingoption
                    $("tr.chooseshippingoption > td").html(html);
                    $("tr.chooseshippingoption").show();
                    $("#accordion").accordion("resize");
                }
            })             
        }
    })
    
    $("#test_lnk_page2").click(function(e){
        e.preventDefault();
        $("#accordion").accordion("activate",1);
    })
        
    $('input[name="order[shipping][shippingOption]"]:radio').live('click',function(){
        // alert('you selected' + this.id);
        $.ajax({
            url: ajax_checkout_uri,
            type: "GET",
            async: true,
            data: 'req=addShipping&opt='+this.id+'&cost='+this.value + '&max='+$(this).attr('rel'),
            success:function(obj){
                var data = eval("(" + obj + ")");
                if(data['result']=='success')
                    updateTotals(data['totals']);
            // console.log(data);
            }
        });
    })
    $("#allToOneAddress").change(function(event){
        alert('Oh no, this needs to be implemented!');
    })
        
    $("#frm_finalize_order").validate({
        rules: {
            "billing[email]": {
                remote: ajax_checkout_uri + '?req=validateEmail'
            }
        },
        messages: {
            "billing[firstName]": {
                required: ''
            },
            "billing[lastName]": {
                required: ''
            },
            "billing[email]": {
                required: '',
                email: '',
                remote: 'Email address already exists in our database! Please <a href="/index.php/checkout/login">login</a> or provide another email address.'
            }
        },
        errorClass: 'error'
    })
        
    $("#btn_billing_continue").click(function(event){   
        // validate billing information                           
            
        $("#frm_order_billing").validate({                
            errorClass: 'error',
            success: function() {
            // save data server side                                       
            },
            submitHandler: function(form){
                                       
                // var data = $.param(form);
                var firstName   = $("#b_firstName").attr('value');
                var lastName    = $("#b_lastName").attr('value');
                var email       = $("#b_email").attr('value');
                var company     = $("#b_company").attr('value');
                var street      = $("#b_street").attr('value');
                var street2     = $("#b_street2").attr('value');
                var city        = $("#b_city").attr('value');
                var country     = $("option:selected",b_country_id).attr('value');
                var region      = $("option:selected",b_region_id).attr('value');
                var zip         = $("#b_zip").attr('value');
                var creditcard  = $("#creditcard").attr('value');
                var securitycode = $("#securitycode").attr('value');
                var exp_month   = $("#expires_month option:selected").attr('value');
                var exp_year    = $("#expires_year option:selected").attr('value');
                    
                var paymentMethod = 'creditcard';
                    
                var xhr = $.ajax({
                    url: ajax_checkout_uri,
                    method: 'POST',
                    data: 'req=saveBillingData&firstName='+firstName+'&lastName='+lastName+'&email='+email+'&company='+company+'&street='+street+'&street2='+street2+'&city='+city+'&zip='+zip+'&region='+region+'&country='+country+'&creditcard='+creditcard+'&securitycode='+securitycode+'&expires_month='+exp_month+'&expires_year='+exp_year+'&paymentMethod='+paymentMethod,
                    success: function(obj) {
                        data = eval('(' + obj + ')');                            
                        // do something
                        $("#billing_firstName").html($("#b_firstName").val());
                        $("#billing_lastName").html($("#b_lastName").val());
                        $("#billing_email").html($("#b_email").val());
                        $("#billing_street").html($("#b_street").val());
                        $("#billing_street2").html($("#b_street2").val());
                        $("#billing_city").html($("#b_city").val());
                        // b_region is set to VA by default....maybe it needs to be set to the shipping region by default
                        $("#billing_region").html( region.length > 0 ? region : $("option:selected",region_id).attr('value') );
                        $("#billing_zip").html($("#b_zip").val());                            

                        $("#cc_billing_info").show();
                        $("#cc_shipping_info").show(); 
                        updateTotals(data['totals']);
                        $("#accordion").accordion("activate",2);
                    }
                })
            },
            rules: {
                "order[billing][creditcard]": {
                    required: true,
                    creditcard: true
                },                
                "order[billing][email]": {
                remote: ajax_checkout_uri + '?req=validateEmail'
            }
            },
            messages: {
                "order[billing][firstName]" : {
                    required: ''
                },
                "order[billing][lastName]" : {
                    required: ''
                },
                "order[billing][street]" : {
                    required: ''
                },
                "order[billing][region]" : {
                    required: ''
                },
                "order[billing][zip]" : {
                    required: ''                        
                },
                "order[billing][email]" : {
                    required: '',
                    email: '',
                    remote: 'Email address already exists. Please <a href="/index.php/checkout/login">Login</a> or provide another password.'
                },
                "order[billing][city]" : {
                    required: ''                        
                },
                "order[billing][creditcard]" : {
                    required: '',
                    creditcard: 'Please enter a valid number'
                },
                "order[billing][securitycode]" : {
                    required: ''                        
                },
                "order[billing][expiration][month]" : {
                    required: ''                        
                },
                "order[billing][expiration][year]" : {
                    required: ''                        
                }
            }
                
        });
    //event.preventDefault();
            
    })
        
        
    $("#lnk_copy_shipping_to_billing").click(function(event){
        // copies the shipping information over the billing information.
        var firstName   = $("#firstName").attr('value');
        var lastName    = $("#lastName").attr('value');
        var email       = $("#email").attr('value');
        $("#billingFirstName").val(firstName);
        $("#billingLastName").val(lastName);
        $("#billingEmail").val(email);
    })
        
    $("#btn_shipping_continue").click(function(event){   
        // validate shipping information                           
            
        $("#frm_order_shipping").validate({                
            errorClass: 'error',
            success: function() {
            // save data server side                                       
            },
            submitHandler: function(form){
                                       
                // var data = $.param(form);
                var firstName   = $("#firstName").attr('value');
                var lastName    = $("#lastName").attr('value');
                var email       = $("#email").attr('value');
                var company     = $("#company").attr('value');
                var street      = $("#street").attr('value');
                var street2     = $("#street2").attr('value');
                var city        = $("#city").attr('value');
                var country     = $("option:selected",country_id).attr('value');
                var region      = $("option:selected",region_id).attr('value');
                var zip         = $("#zip").attr('value');
                    
                var xhr = $.ajax({
                    url: ajax_checkout_uri,
                    method: 'POST',
                    data: 'req=saveShippingData&firstName='+firstName+'&lastName='+lastName+'&email='+email+'&company='+company+'&street='+street+'&street2='+street2+'&city='+city+'&zip='+zip+'&region='+region+'&country='+country,
                    success: function(obj) {
                        data = eval('(' + obj + ')');                            
                        // copy shipping information to the confirm order section
                        $("#shipping_firstName").html($("#firstName").val());
                        $("#shipping_lastName").html($("#lastName").val());
                        $("#shipping_email").html($("#email").val());
                        $("#shipping_street").html($("#street").val());
                        $("#shipping_street2").html($("#street2").val());
                        $("#shipping_city").html($("#city").val());
                        $("#shipping_region").html(region);
                        $("#shipping_zip").html($("#zip").val());                           
                            
                        $("#billing_firstName").html($("#firstName").val());
                        $("#billing_lastName").html($("#lastName").val());
                        $("#billing_email").html($("#email").val());
                        $("#billing_street").html($("#street").val());
                        $("#billing_street2").html($("#street2").val());
                        $("#billing_city").html($("#city").val());
                        $("#billing_region").html(region);
                        $("#billing_zip").html($("#zip").val());  
                        
                        if($("option:selected",country_id).attr('value') != 'US') // hide COD tab
                            $("#tabs").tabs("disable",3);
                        else
                            $("#tabs").tabs("enable",3);
                        
                        $("#accordion").accordion("activate",1);
                        $("#lnk_edit_shipping").show();
                    }
                })
            },
            rules: {
                "order[shipping][region]" : {
                    required: function() {
                        return $("option:selected",country_id).attr('value') == 'US';
                    }
                }
            },
            messages: {
                "order[shipping][firstName]" : {
                    required: ''
                },
                "order[shipping][lastName]" : {
                    required: ''
                },
                "order[shipping][street]" : {
                    required: ''
                },
                "order[shipping][region]" : {
                    required: ''
                },
                "order[shipping][zip]" : {
                    required: ''                        
                },
                "order[shipping][city]" : {
                    required: ''                        
                }
            }
                
        });
    //event.preventDefault();
            
    })
        
    $("#lnk_edit_shipping").click(function(){                    
        $(this).hide();
        setPage(0,selectedTab);
    });
        
    $("#lnk_edit_billing").click(function(){                    
        $(this).hide();
        setPage(1,selectedTab);            
    })
        
    $("#btn_giftcard_continue").click(function(){                                
        setPage(2,selectedTab);
    })
        
    $("#lnk_confirm_order").click(function(){                    
        $(this).hide();
        setPage(2,selectedTab);            
    })
        
    $("a.promolnk").click(function(e){
        e.preventDefault();
        $(this).toggle();
        $("#promoinputbox").toggle();
    });
        
    $("a.promosubmitlnk").click(function(e){
        e.preventDefault();
        var promoinput = $("#inputpromocode");
        promoinput.removeClass('error');
        var promocode = promoinput.attr('value');
        if(promocode != '')
        {
            var xhr = $.ajax({
                url:      ajax_checkout_uri,
                type:     "GET",
                data:     'req=addCoupon&coupon=' + promocode,
                success: function(obj){
                    var data = eval("(" + obj + ")");
                    if(data['result']=='failure')
                    {
                        promoinput.addClass('error');
                    }
                    else
                    {
                        // console.log(data);
                        updateTotals(data['totals']);
                        if(parseInt(data['totals']['couponValue']) > 0)
                        {
                            $("tr[class=coupon]").fadeIn();
                        }
                        else
                        {
                            $("tr[class=coupon]").fadeOut();
                        }                            
                    }
                // $("#notice").html(val).fadeIn().delay(5000).fadeOut();                      
                }
            // {"couponValue":10.00,"total":136.00,"tax":6.80}
            })
        }
    });
    if(country_id.length > 0) {
        if($.inArray($("option:selected", country_id).text(),worldRegions))
        {
            region_id.show();
            var country = $("option:selected",country_id).attr('value');
            $.each(worldRegions[country],function(i){
                $("#region_id").append($('<option>', {
                    'value' : worldRegions[country][i]['code']
                }).text(worldRegions[country][i]['name']));
            // console.log(worldRegions['US'][i]['name']);              
            });
            $("#region_id").val($("#region").attr('value'));
        }

        country_id.change(function(){
            var country = $("option:selected",country_id).attr('value');
            var found = false;
            $.each(worldRegions,function(i,val){                
                if(i == country)
                    found = true;
            })            
            if(found)
            {               
                
                $("#region_id").html('<option value="">Please select region, state or province</option>');
                $.each(worldRegions[country],function(i){                    
                    $("#region_id").append($('<option>', {
                        'value' : worldRegions[country][i]['code']
                    }).text(worldRegions[country][i]['name']));
                // console.log(worldRegions['US'][i]['name']);
                $("#region_id").show();
                });              
            }
            else
            {
                $("#region_id").hide();
                $("#region_id").val('');
            }
        });
    }
    if(b_country_id.length > 0 ){
    if($.inArray($("option:selected", b_country_id).text(),worldRegions))
    {
        b_region_id.show();
        var country = $("option:selected",b_country_id).attr('value');
        $.each(worldRegions[country],function(i){
            $("#b_region_id").append($('<option>', {
                'value' : worldRegions[country][i]['code']
            }).text(worldRegions[country][i]['name']));
        // console.log(worldRegions['US'][i]['name']);              
        });
        $("#b_region_id").val($("#b_region").attr('value'));
    }

    b_country_id.change(function(){
        var country = $("option:selected",b_country_id).attr('value');
        var found = false;
        $.each(worldRegions,function(i,val){                
            if(i == country)
                    found = true;
            })            
        if(found)
        { 
            b_region_id.html('<option value="">Please select region, state or province</option>');
            $.each(worldRegions[country],function(i){
                b_region_id.append($('<option>', {
                    'value' : worldRegions[country][i]['code']
                }).text(worldRegions[country][i]['name']));
            // console.log(worldRegions['US'][i]['name']);
            b_region_id.show();
            });              
        }
        else
        {
            b_region_id.hide();
        }
    });
    }
    myForm.validate({            
        errorClass: "error",
        onkeyup: false,
        success: function(error, element) {
            setTimeout(function(){
                // myForm.find('input.valid').qtip('destroy');                    
                },1)
                
                
        },
        errorPlacement: function(error, element){
            // console.log(error);
                
            if(error[0].textContent.length > 0)
                $("#warning").html(eval(error)).fadeIn().delay(5000).fadeOut();
        // $(element).find('span.formtip').html(eval(error));
                
        },
        rules: {
            email: {
                required: true,
                email: true
            },
            password: {
                required: true
            }
        },
        messages: {
            password: {
                required: 'Please enter your password'
            }
        }
    })
  
    /* HOMEPAGE */
  
    $(".slideshow").cycle({
        activePagerClass: 'selected',
        fx: 'fade',
        pager: '.navi',
        timeout: 5000
    });

    $("#search_btn").click(function(event){
        event.preventDefault();
    });
    $("#mailinglist_btn").click(function(event){
        event.preventDefault();
    });
    $("#viewcart_lnk").hover(
        function(){
            // mouseenter
            $.ajax({
                url: ajax_uri,
                data: {
                    'req' : 'viewcart'
                },
                type: "GET",
                cache: false,
                beforeSend: function()
                {
                    $("#cart").html('<p><span>loading....</span></p>').toggle();
                },
                success: function(content)
                {
                    $("#cart").html(content);
                }
            })
        },
        function(){
            $("#cart").toggle();
        });

    $('#search_txt_input').focus(function(){
        var val = $(this).attr('value');
        $(this).attr('value','');
    }).blur(function(){
        if($(this).attr('value')=='') {
            $(this).attr('value','Search MOONRISE Jewelry');
        } 
    });

    function log(message)
    {
        $("<div />").text(message).prependTo("#log");
        $("#log").scrollTop( 0 );
    }
    // searchbox autocomplete code
    $("#search_txt_input2").autocomplete({
        source: ajax_uri + '?req=search',
        minLength: 2,
        select: function(event, ui) {
            if(ui.item.url.length > 0)
            {
                window.location = ui.item.url;
            }
        }
    });



    
    /* PRODUCT DETAIL */    

    // $("ul.tabs").tabs("div.panes > div");
    if($.scrollable)
        $(".matches").scrollable();
          
    // scroller  = new jsScroller(document.getElementById("Information"), 400, 180);
    // scrollbar = new jsScrollbar (document.getElementById("Scrollbar-Container"), scroller, true, scrollbarEvent);
          
    $("#Information1").tinyscrollbar({
        scroll: true
    });
    $("#Review1").tinyscrollbar({
        scroll: true
    });
    $("#Maintenance1").tinyscrollbar({
        scroll: true
    });

    $("#zoomer").hover(function(){
        $("#zoomer-big").toggle();
    },function(){
        $("#zoomer-big").toggle();
    })

    $("#addProductToCart_btn").click(function(event){
        event.preventDefault();
        var quantity = $("#quantity");
        quantity.removeClass( 'error' );
        var isValid = true;
        // check if quantity is a number
        if( isNaN(quantity.val()) || quantity.val() == 0  ) 
        {
            quantity.addClass('error');
            isValid = false;
        }
        
        // check if this product has any options, and if so if they have been selected
        
        var option = '';
        var pid = $(this).attr('rel');
        var i = 0;
        $("select").each(function(){
            if(  $(this ).attr( 'id' ) != 'me_state' && $( this ).attr('id') != 'me_country')
            {
                $( this ).removeClass( 'error' );
                if($('option:selected',this).val() == 'Choose to select option')
                {
                    isValid = false;
                    $( this ).addClass( 'error' );
                }
                else
                {
                    option += '&opt['+i+']='+$('option:selected',this).attr('value');
                    i++;
                }
            }
        })
        if(isValid) // no input errors detected. proceed to add item to cart
        {
            var xhr = $.ajax({
                type: 'GET',
                url: ajax_uri,
                data: "id=" + pid + "&qty="+ quantity.val() + "&req=addToCart" + option,
                success: function(msg){
                    $("#notice").html(msg).fadeIn().delay(10000).fadeOut();
                }
            });
        }
    });
    
    
    /* CART */

/*
    if($.inArray($("#cart_country option:selected").text(),worldRegions))
    {
        $("#cart_region_id").show();
        var country = $("#cart_country option:selected").attr('value');
        $.each(worldRegions[country],function(i){
            $("#cart_region_id").append($('<option>', {
                'value' : worldRegions[country][i]['code']
            }).text(worldRegions[country][i]['name']));
        // console.log(worldRegions['US'][i]['name']);
        });
    }

    $("#cart_country").change(function(){
        var country = $("#cart_country option:selected").attr('value');
        if($.inArray(country,worldRegions))
        {
            $("#cart_region_id").html('<option value="">Please select region, state or province</option>');
            $.each(worldRegions[country],function(i){
                $("#cart_region_id").append($('<option>', {
                    'value' : worldRegions[country][i]['code']
                }).text(worldRegions[country][i]['name']));
            // console.log(worldRegions['US'][i]['name']);
            });
        }
        else
        {
            $("#cart_region_id").hide();
        }
    });
*/
    $("#frm_shippingQuote").validate({
        submitHandler: function(){
            var xhr = $.ajax({
                url: ajax_uri,
                type: "GET",
                data: 'req=shippingQuote&country=' + $("#cart_country option:selected").val() + '&region=' + $("#cart_region_id option:selected").val(),
                success: function(obj){
                    var data = eval("(" + obj + ")");
                    // console.log(data);
                    // update Cart Totals
                    /*
                    $.each(data,function(i,val){
                        if(i != 'reply' && i != 0){
                            // console.log("i: " + i + " val: " + val);
                            $("#" + i).html("$" + val);
                        }
                    });
                  
                    // hide tax row if tax not applicable
                    if(data['tax'] > 0) {
                        $("tr[class=tax]").fadeIn();
                    } else  {
                        $("tr[class=tax]").fadeOut();
                    }
                    */
                    var mydata = "<dl class='shipping-methods'>";
                    var target = $("#shipping_form");
                    target.children().remove();
                    $.each(data[0], function(i,val) {
                        mydata += "<dt>"+ i + "</dt><dd><ul>";
                        var myclass = i;
                        $.each(val, function(i,val) {
                            // mydata += "<li><input type='radio' name='shipping' class='radio' id='" + myclass + ' - ' + i + "' value='" + val['price'] + "'>";
                            mydata += "<li><label>" + i + "</label>";
                            mydata += "<span>$" + val['price'].toFixed(2) + "</span></li>";
                        });
                        mydata += "</ul>";
                    });
                    mydata += "</dd></dl>";
                    target.append(mydata);

                    $("#shippingQuote").show();                    
                }
            })
        }
    });
          
    $("input[name=shipping]").live('change',function(){
        // if any of the radio buttons change, grab the price and add it to the cart.
        $.ajax({
            url: ajax_uri,
            type: "GET",
            async: true,
            data: 'req=addShipping&opt='+this.id+'&cost='+this.value,
            success:function(obj){
                var data = eval("(" + obj + ")");
                // console.log(data);

                $.each(data,function(i,val){
                    if(i != 'reply' && i != 0){
                        // console.log("i: " + i + " val: " + val);
                        $("#" + i).html("$" + val);
                    }
                    else if (i == 'reply' && val != '') {
                        $("#notice").html(data['reply']).fadeIn().delay(5000).fadeOut();
                    }
                });
                // add description to shipping & handling tag
                $("span .sh-selected-option").html('(' + data['shippingOption'] + ')');
                $("span .shippingCost").html('$ ' + data['shipping']);
                $("tr[class=shipping]").fadeIn();
            }
        })
    });
          
    /*
          *     TODO: 
          *     this must all be refactored, much to complicated and cumbersome to maintain
          *     rewrite so there is a simple updateCart function which sends the item index and new qty to the server
          *     then call an update table method which removes any row with a qty of zero.
          *     then call the update totals (if necessary)
           */
          
          
    $("#lnk_item_delete").live('click',function(event)
    {
        event.preventDefault();
            
        var idx = $(this).attr('name');
            
        // set qty to zero for selected input box
            
        if(confirm('Are you sure?')) 
        {
            $('#' + idx).attr('value',0);
                
            var ids = updateCartTable();
            var xhr=$.ajax({
                url: ajax_uri,
                type: "GET",
                data: 'req=updateCart&data='+ ids,
                success: function(obj)
                {
                    // push msg into notification zone
                    var data = eval("(" + obj + ")");
                    // console.log(data);
                    $.each(data,function(i,val){
                        if(i != 'reply'){
                            // console.log("i: " + i + " val: " + val);
                            $("#" + i).html("$" + val);
                        } else {
                            $("#notice").html(val).fadeIn().delay(5000).fadeOut();
                        }
                    })
                }
            });
                
        }
            
    })


    $("#coupon_btn").click(function(event){
        event.preventDefault();
        var xhr = $.ajax({
            url:"<?php echo url_for('ajax'); ?>",
            type: "GET",
            data: 'req=addCoupon&coupon='+$("#coupon").attr('value'),
            success: function(obj){
                var data = eval("(" + obj + ")");
                // console.log(data);
                $.each(data,function(i,val){
                    if(i != 'reply'){
                        // console.log("i: " + i + " val: " + val);
                        $("#" + i).html("$" + val);
                    } else {
                        if(parseInt(data['couponValue']) > 0)
                        {
                            $("li[class=coupon]").fadeIn();
                        }
                        else
                        {
                            $("li[class=coupon]").fadeOut();
                        }
                        $("#notice").html(val).fadeIn().delay(5000).fadeOut();
                    }
                })
            // {"couponValue":10.00,"total":136.00,"tax":6.80}
            }
        })
    });

    $("#updateCart_lnk").click(function(event)  {
        event.preventDefault();
        // first step, get all quantities and ids
        // domEle == this
            
        var ids = updateCartTable();

        $.ajax({
            url: ajax_uri,
            type: "GET",
            data: 'req=updateCart&data='+ids,
            success: function(obj){
                var data = eval("(" + obj + ")");
                // console.log(data);
                $.each(data,function(i,val){
                    if(i != 'reply'){
                        // console.log("i: " + i + " val: " + val);
                        $("#" + i).html("$" + val);
                    } else {
                        $("#notice").html(val).fadeIn().delay(5000).fadeOut();
                    }
                    
                });
                $("#cartsubtotal").html(data['subTotal']);
            // update table
            }
        });
    })
    
    
/* CHECKOUT LOGIN */


$("#frm_login").validate({            
    errorClass: "error",
    success: function(error, element) {
        setTimeout(function(){
            // myForm.find('input.valid').qtip('destroy');                    
        },1)
    },
    errorPlacement: function(error, element){
        // console.log(error);

        if(error[0].textContent.length > 0)
            $("#warning").html(eval(error)).fadeIn().delay(5000).fadeOut();
        // $(element).find('span.formtip').html(eval(error));

    },
    rules: {
        email: {
            required: true,
            email: true
        },
        password: {
            required: true
        }
    },
    messages: {
        email: {
            required: 'Please enter your email address'
        },
        password: {
            required: 'Please enter your password'
        }
    }
});
    
/* CHECKOUT */
    

});

