﻿//////////////////////////////////////////////////////////////////////
// extends the jQuery $ function and adds json stringification
//////////////////////////////////////////////////////////////////////
(function($) {
    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    },
        s = {
            'array': function(x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function(x) {
                return String(x);
            },
            'null': function(x) {
                return "null";
            },
            'number': function(x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function(x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function(x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    $.toJSON = function(v) {
        var f = isNaN(v) ? s[typeof v] : s['number'];
        if (f) return f(v);
    };

    $.parseJSON = function(v, safe) {
        if (safe === undefined) safe = $.parseJSON.safe;
        if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
            return undefined;
        return eval('(' + v + ')');
    };

    $.parseJSON.safe = false;

})(jQuery);


var firebug = ("console" in window && "firebug" in console);

//////////////////////////////////////////////////////////////////////
// rec_event function
  function rec_event(d) {
    if (typeof d == "object") { d = $.toJSON(d); }
    $('#events ol').append('<li>' + d + '</li>');
}
//////////////////////////////////////////////////////////////////////
// debug text
function debug(o) {
    if (typeof o == "object") { o = $.toJSON(o); }
    $('#debug').html(o);
}


//////////////////////////////////////////////////////////////////////
// json arrays like to think they're objects when you do a typeof
// this will identify an array as an array
function isArray(object) {
    return object != null && typeof object == "object" && 'splice' in object && 'join' in object;
}

//////////////////////////////////////////////////////////////////////
// need to make this remove attributes from a not in b
var merge_data = function(a, b) {
    for (z in b) { a[z] = b[z]; }
    return a;
}

// this is a hack to get selected things to show up using f-exist or f-sel
function setExisting(ws, type, category, id) {
    var c = category.toLowerCase(), tmpar = [];
    if (isArray(u[ws][category])) { u[ws][category] = []; }
    else { u[ws][category] = ''; }
    if (p[type][id][c + '-exist']) { tmpar = []; u[ws][category] = tmpar.concat(p[type][id][c + '-exist']); }
    if (p[type][id][c + '-sel']) { tmpar = []; u[ws][category] = tmpar.concat(p[type][id][c + '-sel']); }
}
//////////////////////////////////////////////////////////////////////
// reformat product data & setup what's selected in the user object
// keep says if you should keep the existing object or overwrite the entire thing
function reformat(re, ws) {
    // get the list of categories for this silo, e.g.; P,L,F,E,C
    var l = p.siloCategories[ws], tmpar = [];

    for (t = 0, T = l.length; t < T; t++) {

        if (re[l[t]]) {

            if (ws != 'w') {
                //add in what's existing or selected to the user object
                if ((!u[ws][l[t]]) || (u[ws][l[t]] == '')) {


                    if (!u[ws][l[t]]) {
                        if ((l[t] == 'P') || (l[t] == 'L') || (l[t] == 'I')) { u[ws][l[t]] = 0; }
                        else { u[ws][l[t]] = []; }
                    }

                    if (isArray(u[ws][l[t]])) {
                        if (re[l[t]].exist) {
                            if (isArray(re[l[t]].exist)) { tmpar = []; u[ws][l[t]] = tmpar.concat(re[l[t]].exist); }
                            else if (re[l[t]].exist != 0) { u[ws][l[t]].push(re[l[t]].exist); } // existing
                        }
                        if (re[l[t]].sel) {
                            if (isArray(re[l[t]].sel)) { tmpar = []; u[ws][l[t]] = tmpar.concat(re[l[t]].sel); }
                            else if (re[l[t]].sel != 0) { u[ws][l[t]].push(re[l[t]].sel); } // selected (overrides existing if present) and also changes the typeof
                        }

                    }

                    else {

                        if (re[l[t]].exist) {
                            if (isArray(re[l[t]].exist)) { tmpar = []; u[ws][l[t]] = tmpar.concat(re[l[t]].exist); }
                            else if (re[l[t]].exist != 0) { u[ws][l[t]] = re[l[t]].exist; } // existing
                        }
                        if (re[l[t]].sel) {
                            if (isArray(re[l[t]].sel)) { tmpar = []; u[ws][l[t]] = tmpar.concat(re[l[t]].sel); }
                            else if (re[l[t]].sel != 0) { u[ws][l[t]] = re[l[t]].sel; } // selected (overrides existing if present)
                        }

                    }
                    if (u[ws][l[t]] === 0) { u[ws][l[t]] = ''; } // if something = 0 then null it
                }
            }

            if (re.internetqual) {
                // change zt qual to this value
                u.i.qual = re.internetqual;
            }
            
            // loop thru and move the products up a level
            if (re[l[t]].list) {
                re[l[t]].total = re[l[t]].list.length;

                if (l[t] == 'H') {p.phone_sorts = p.phone_cats; } // reset phone sort array
                for (var i in re[l[t]].list) {

                    var li = re[l[t]].list[i];
                    re[l[t]][li.id] = li;
                    // if existing but not keepable, remove from user object
                    // ***** needs rework to remove items from an array, not just null it out *****//
                    if (li.keep == false) { isArray(u[ws][l[t]]) ? u[ws][l[t]] = [] : u[ws][l[t]] = ''; }

                    // apply attributes
                    if (li.attrs) {
                        
                        var bobo = [], attributes = bobo.concat(li.attrs);
                        delete li.attrs;
                        li.attrs = {};
                        for (a = 0, A = attributes.length; a < A; a++) {
                            if (re.A[attributes[a]]) {
                                if ((re.A[attributes[a]].val == undefined) || (re.A[attributes[a]].val == '')) { re.A[attributes[a]].val = true; }
                                li.attrs[re.A[attributes[a]].name.toLowerCase()] = re.A[attributes[a]].val;

                                // create phone sort data for p.phone_sorts
                                if (l[t] == 'H') {
                                    if (p) {
                                        if (p.phone_sorts) {
                                            if (p.phone_sorts.types) {
                                                if (p.phone_sorts.types[re.A[attributes[a]].name.toLowerCase()]) {
                                                    p.phone_sorts.types[re.A[attributes[a]].name.toLowerCase()].phones.push(li.id);
                                                }
                                            }
                                            if (p.phone_sorts.features) {
                                                if (p.phone_sorts.features[re.A[attributes[a]].name.toLowerCase()]) {
                                                    p.phone_sorts.features[re.A[attributes[a]].name.toLowerCase()].phones.push(li.id);
                                                }
                                            }
                                        }
                                    }
                                }
                                // end phone sort data
                            }
                        }
                    }

                    // change max values to blank if it's an int.max
                    if (l[t] == 'D') {
                        if (li.max) {
                            if (li.max > 1000) { li.max = ''; }
                        }
                    }

                    // change all m2m features to standard
                    if (l[t] == 'F') {
                        if (li.t) {
                            if (li.t.toLowerCase() == 'mobiletomobile') { li.ft = 'Standard'; }
                        }
                    }

                    if (li.qty) {
                    u[ws][l[t] + li.id + 'q'] = li.qty;
                    }

                 
                    // apply phone pricing
                    if (l[t] == 'H') {
                        for (var d = 0, D = li.pro.length; d < D; d++) {
                            var lr = re.D[li.pro[d]];
                            var lrp = lr.price;
                            switch (lr.t.toLowerCase()) {
                                case 'cbwinstantdiscount':
                                    li.instant ? li.instant += lrp : li.instant = lrp; break;
                                case 'cbwautoapply':
                                    li.auto ? li.auto += lrp : li.auto = lrp; break;
                                case 'cbwselectablediscount':
                                    li.selectable = lrp; break;
                                case 'cbwrebate':
                                    li.rebate ? li.rebate += lrp : li.rebate = lrp; break;
                                case 'cbwcontract':
                                    li.contract ? li.contract += lrp : li.contract = lrp; break;
                                default:

                            }
                        }
                    }
                    // if has existing users, push em into the wireless user collection
                    else if (l[t] == 'existing') {
                        var newu = {
                            id: li.id,
                            nickname: formatPhone(li.nickname) || "'s Phone",
                            device: li.device,
                            dkeep: true,
                            pkeep: true,
                            plan: li.plan,
                            features: li.feats,
                            accessories: li.accessories,
                            type: 'e', // existing
                            tmp: false,
                            t: {},
                            ex: {
                                device: li.device,
                                plan: li.plan,
                                features: li.feats,
                                accessories: li.accessories
                            },
                            pro: li.promos,
                            wantscontract: li.wantscontract,
                            mustchangeplan: li.mustchangeplan,
                            undercontract: li.undercontract,
                            cangetcontract: li.cangetcontract,
                            yp42: li.yp42confirmation
                        }
                        u.add_user(newu);
                        // set the global plan type
                        if (li.plan) {
                            if (re.RP[li.plan]) {
                                if (re.RP[li.plan].t == 1) {
                                    u.w.users.plan_type = re.RP[li.plan].t;
                                    u.w.users.shared_plan = re.RP[li.plan].id;
                                }
                            }
                        }
                        if (re.addonlimit) { u.w.users.addonlimit = re.addonlimit; }
                      
                        u.wcount();
                    }
                    // if has existing users, push em into the wireless user collection
                    else if (l[t] == 'incart') {

                        var newu = {
                            id: li.id,
                            nickname: formatPhone(li.nickname) || "'s Phone",
                            device: li.device,
                            dkeep: false,
                            pkeep: false,
                            plan: li.plan,
                            features: li.feats,
                            accessories: li.accessories,
                            type: 'i', // incart
                            incart: true,
                            tmp: false,
                            t: {},
                            pro: li.promos,
                            wantscontract: li.wantscontract,
                            mustchangeplan: li.mustchangeplan,
                            undercontract: li.undercontract,
                            cangetcontract: li.cangetcontract,
                            yp42: li.yp42confirmation
                        }

                        if (u.w.users) {
                            if (u.w.users[li.id]) {
                                if (u.w.users[li.id].type == 'e') {
                                    newu.ex = u.w.users[li.id].ex;
                                }
                                if (newu.device == '-1') { newu.device = u.w.users[li.id].device; newu.dkeep = true; }
                                if (newu.plan == '-1') { newu.plan = u.w.users[li.id].plan; newu.pkeep = true; }
                            }
                        }

                        if (newu.device == '-1') { newu.device = '';  li.device = ''; }
                        if (newu.plan == '-1') {newu.plan = '';  li.plan = ''; }
                       
                        u.add_user(newu);
                        // set the global plan type
                        if (li.plan) {
                            if (re.RP[li.plan]) {
                                u.w.users.plan_type = re.RP[li.plan].t;
                                u.w.users.shared_plan = re.RP[li.plan].id;
                            }
                        }
                        u.wcount();
                    }
                    
                    delete li;
                }
                delete re[l[t]].list;
            }


            if (l[t] == 'rules') { // rules
                re.R = {};
                for (var ri in re[l[t]]) {
                    re.R[re[l[t]][ri].id] = re[l[t]][ri];
                }
                delete re[l[t]];
            }
            if ((l[t] == 'existing') || (l[t] == 'incart')) { delete re[l[t]]; }
        }   
    }
    return re;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// split price
////////////////////////////////////////////////////////////////////////////////////////////////////
function splitPrice(price, parent, cid, orig_price, included, asbilled) {
    if (orig_price == undefined) { orig_price = 0; }

    var parray = parseFloat(price).toFixed(2).split(".");
    parray[2] = '$', parray[3] = '.', parray[4] = 'per month'; parray[5] = orig_price;

    if ((orig_price > price)) { parray = orig_price.toFixed(2).split("."); parray[2] = '$', parray[3] = '.', parray[4] = 'per month'; parray[5] = price; } 
    
    if (parent) { if (parent.exist == cid) { parray = ['', '<a href="#" '+abclick+'><b>As Billed</b></a>', '', '', '']; } }    
    if ((price == 0) && ((orig_price <= price)) && (parray[1].indexOf('<') != 0) && included) { parray = ['', '<b>Included</b>', '', '', '']; }
    if (asbilled) { parray = ['', '<a href="#" ' + abclick + '><b>As Billed</b></a>', '', '', '']; }
   
    
    if (parseInt(parray[0]) < 0) { parray[0] = 0; }
    if (cid == '1210000') { parray[1] = '<b></b>'; }
    return [parray[2] + parray[0], parray[3] + (parray[1] ? parray[1] : '00'), parray[4], parray[5], parray[0] + '.' + parray[1]];
}


function sortBy(a, b) {
    var x = b.install | b.price;
    var y = a.install | a.price;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByReverse(b, a) {
    var x = b.install | b.price;
    var y = a.install | a.price;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByAttr(a, b) {
    var x = b.attrs.sort | 0;
    var y = a.attrs.sort | 0;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}



// garbage function, can throw away
function prettyformat(inn) {
    inn = inn.replace(/\{/g, '<br>{<blockquote>');
    inn = inn.replace(/\}/g, '</blockquote>}<br>');
    inn = inn.replace(/\,/g, ',<br>');
    return inn;
}
function formatPhone(i) {
    if (i) {
        return i.replace(/([0-9]{3})([0-9]{3})([0-9]{4})/, "( $1 ) $2-$3");
    }
    else { return ''; }
}
function arrayDiff(v, c, m){
    var d = [], e = -1, h, i, j, k;
    for(i = c.length, k = v.length; i--;){
        for(j = k; j && (h = c[i] !== v[--j]););
        h && (d[++e] = m ? i : c[i]);
    }
    return d;
}

function formatAddress(a) {
    if (a) {
        if (!a.fn) { a.fn = ''; }
        var da = '<div class="address_left"><b>' + a.fn + '</b><br/>' + a.adr + '<br/>' + a.cty + ', ' + a.st + ' ' + a.zip;
        if ((a.acct || a.id) && (a.id != 'N')) { da += '<br/><b class="green">Acct #: ' + (a.acct || a.id) + '</b>'; }
        da += '</div>';
        return da;
    }
    return '';
}

function shrinkAddress(a) {
    if (a) {
        var sa = a.fn + ' ' + a.adr + ' - ' + a.cty + ' ' + a.st + ', ' + a.zip;
        sar = sa.split('');
        sa = '';
        for (q = 0; q < 45; q++) {
            if (!sar[q]) { break; }
            sa += sar[q];
        }
        if (sar.length > 45) { sa += '...'; }
        return sa;
    }
    return ''
}



function sanitize(o) {
    if (o == undefined) { o = ''; }
    if (typeof o == "string") {
        return o.replace(/\'s |phone| $|\'|\n|\r|\t|\"|\;|\*|\^|\%|\(|\)|\+|\:|\/|\?|\>|\<|\\|\!|\@|\#|\$|\&|\||\]|\[|\{|\}|\_|\~|\`|\=/ig, "");
    } else { return ''; }
}

// clean me up santa!
function santatize(o) {
    if (o == undefined) { o = ''; }
    if (typeof o == "string") {
    return o.replace(/\$|\'|\n|\r|\t|\"|\;|\*|\^|\%|\(|\)|\+|\:|\/|\?|\>|\<|\\|\!|\@|\#|\$|\&|\||\]|\[|\{|\}|\_|\~|\`|\=/ig, "");
} else { return ''; }
}


function unique(a) {
    var r = new Array();
    o: for (var i = 0, n = a.length; i < n; i++) {
        for (var x = 0, y = r.length; x < y; x++) {
            if (r[x] == a[i]) continue o;
        }
        r[r.length] = a[i];
    }
    return r;
}



var bunit = {
    timer: null,
    enterprise: '/business/enterprise/',
    soho: '/business/soho/',
    smb: '/business/smb/',
    res: '/consumer/',
    enterprise_left: 471,
    soho_left: 130,
    smb_left: 310,
    res_left: 6,
    status: false,
    toggle: function() { this.status ? this.close() : this.open(); },
    toggletab: function(i, re) { this.status ? i == 'over' ? this.over(re) : this.off(re) : i == 'over' ? $('#rb_updown').addClass('change') : $('#rb_updown').removeClass('change'); },
    over: function(re) {
        clearTimeout(this.timer);
        $('#rb_bubble').css({ display: 'block' }).animate({ left: (this[re + '_left'] - 5) + 'px' }, 'fast');
        this.bubble_size(re);
    },
    bubble_size: function(re) { re == 'res' ? $('#rb_bubble').addClass('short') : $('#rb_bubble').removeClass('short'); },
    off: function() {
        clearTimeout(this.timer);
        var re = (this[$('#bunitsinner').attr('class') + '_left'] - 5) + 'px';
        this.timer = setTimeout("$('#rb_bubble').animate({ left: '" + re + "' }, function() { bunit.bubble_size('" + $('#bunitsinner').attr('class') + "'); $('#rb_bubble').css({ display: 'block' }); })", 500);
    },
    link: function(r) { this.status ? location.href = this[r] : bunit.open(); },
    open: function() {
        $('#locinner').animate({ opacity: 0 });
        $('#resbiz').animate({ left: '5px' });
        $('#rb_clip').animate({ width: '640px', marginLeft: '15px' }, function() { bunit.status = true; bunit.off(); });
        $('#bunitstop').animate({ height: '50px', paddingTop: '20px' });
        $('#rb_updown').removeClass('change');
        $('#rb_updown').addClass('close');

    },
    close: function() {
        $('#locinner').animate({ opacity: 100 });
        $('#rb_bubble').css({ display: 'none' });
        $('#resbiz').animate({ left: '-293px' });
        $('#rb_clip').animate({ width: '150px', marginLeft: 0 });
        $('#bunitstop').animate({ height: '32px', paddingTop: '0' });
        $('#rb_updown').removeClass('change');
        $('#rb_updown').removeClass('close');
        this.status = false;
    },
    bubble: function(x) { $('#rb_bubble').animate({ left: x }); }
}



var loc = {
    timer: null,
    status: false,
    toggle: function() { this.status ? this.close() : this.open(); },
    open: function() {
        $('#rb_clip').animate({ opacity: 0 });
        $('#rb_updown').animate({ opacity: 0 });
        $('#bunitstop').animate({ height: '80px', paddingTop: '40px' });
        $('#your_location').animate({ marginTop: '6px' }, function() { $('#your_location').attr('src', '/shop/images/selectlocation.png'); $('#your_location').addClass('sel'); });
        $('#my_loc').animate({ marginTop: '5px', marginLeft: '15px' });
        $('#locinner').animate({ width: '750px', marginRight: '200px' }, function() {
            $('#loc_mes').css({ display: 'block' });
            $('#my_loc').css({ display: 'none' });
            $('#sel_region').css({ display: 'block' });
            $('#loc_updown').addClass('close');
        });
        this.status = true;

    },
    close: function() {
        $('#sel_region').css({ display: 'none' });
        $('#rb_clip').animate({ opacity: 100 });
        $('#rb_updown').animate({ opacity: 100 });
        $('#resbiz').animate({ left: '-293px' });
        $('#bunitstop').animate({ height: '32px', paddingTop: '0' });
        $('#your_location').css({ marginTop: '0' });
        $('#your_location').attr('src', '/shop/images/yourlocation.png');
        $('#your_location').removeClass('sel');
        $('#my_loc').css({display: 'block'}).animate({ marginTop: 0, marginLeft: 0 });
        $('#locinner').animate({ width: '255px', marginRight: 0 });
        $('#loc_updown').removeClass('close');
        this.status = false;
    }
}

function val_email(e) {
 var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 if (pattern.test(e)) { return e; }
 return '';
}

function createCookie(name, value, days, domain) {
var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    wholecookie = name + "=" + value + expires + "; path=/;";
    if (domain) { wholecookie = wholecookie + "domain=" + domain + ";"; }
    document.cookie = wholecookie;
}



function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


// Error tracking function
// err: a string or an Error object
function trackError(err) {
    var msg = 'Unknown error';
    if (err.message) {
        msg = err.message;
    }
    else if (typeof err == 'string' || typeof err == 'String') {
        msg = err;
    }
    alert('Tracking error: ' + msg);
};

// override jQuery.fn.bind to wrap every provided function in try/catch
var jQueryBind = jQuery.fn.bind;
jQuery.fn.bind = function(type, data, fn) {
    if (!fn && data && typeof data == 'function') {
        fn = data;
        data = null;
    }
    if (fn) {
        var origFn = fn;
        var wrappedFn = function() {
            try {
                origFn.apply(this, arguments);
            }
            catch (ex) {
                trackError(ex);
                // re-throw ex iff error should propogate
                // throw ex;
            }
        };
        fn = wrappedFn;
    }
    return jQueryBind.call(this, type, data, fn);
};




function makewindow(url, name, wi, hi, scroll) {
    if (!scroll) { scroll = 0; }
    mywin = window.open(url, name, 'width=' + wi + ',height=' + hi + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll);
}



// image preloader
(function($) {
    var img_cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--; ) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            img_cache.push(cacheImage);
        }
    }
})(jQuery)

$.preLoadImages("/shop/images/midmodal.png", "/shop/images/modal.png");