﻿/*** remove with hp ***/

var ieversion = null;

//test for MSIE x.x;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
    ieversion = new Number(RegExp.$1);
}

function searchreviews(qstring) {
    window.location = '/review/advsearch.aspx?t=' + encodeURIComponent(qstring);
}

function clearcell(cleartext, textfield) {
    if (textfield.value == cleartext) {
        textfield.value = '';
    }
}

function hideAdvSearch() {
    if (ieversion != null) {
        if (ieversion < 7) {
            document.getElementById("advsearchd").style.display = 'none';
        }
    }
}

function showAdvSearch() {
    if (ieversion != null) {
        if (ieversion < 7) {
            document.getElementById("advsearchd").style.display = 'block';
        }
    }
}

function buyButtonClick(type, productName, linkLoc) {
    _gaq.push(['_trackEvent', 'BuyButtonClick', type, productName]);
}

function searchgoogle(elem) {
    var tag = document.getElementById(elem),
        val = tag !== null ? tag.value : elem;

    // window.location='http://www.laptopmag.com/search-results.aspx?q=' + encodeURIComponent(qstring) + '&cx=011239505048760151329%3axtwjxuvb8mo&cof=FORID%3a11';
    window.location = 'http://www.laptopmag.com/search.aspx?q=' + encodeURIComponent(val);
}

function clearCtrl(obj) {
    var temp = document.getElementById(obj);

    if (temp !== null) {
        temp.value = '';
    }
}

function showCtrl(obj) {
    var temp = document.getElementById(obj);

    if (temp !== null) {
        temp.style.display = 'block';
    }
}

function hideCtrl(obj) {
    var temp = document.getElementById(obj);

    if (temp !== null) {
        temp.style.display = 'none';
    }
}

function trackclick(d, r, n) {
    if (n === undefined) {
        n = '';
    }
    //if (document.images) {
    //    (new Image()).src = "http://www.laptopmag.com/feeds/ct.php?r=" + r +
    //    "&d=" + d + "&n=" + n;
   // }

    _gaq.push(["_trackEvent", "nav_click", d, n]);

    return true;
}

function trackrevshop(d, r) {
    var n = 'pg_revpull';

    if (d.substr(0, 17) == '/review/shop.aspx') {
        if (document.images) {
            (new Image()).src = "http://www.laptopmag.com/feeds/ct.php?r=" + r + "&d=" + d + "&n=" + n;
        }
    }

    window.location = d;
}

function changeClass(id, classname) {
    //if (document.getElementById('TopNavMarquee').style.display == 'block') { return false; }
    var obj = document.getElementById(id);
    obj.className = classname;
}
function ShowTab(tabName, sender) {
    // if (document.getElementById('TopNavMarquee').style.display == 'block') { return false; }
    sender.className = '';
    var obj = document.getElementById('sidebarContent');
    obj.className = tabName;
}

function r_focus(me, txt) {
    if (me.value == txt) {
        me.value = "";
    }
}

function r_blur(me, txt) {
    if (me.value == "") {
        me.value = txt;
    }
}

/****************************************/
/* Author: Brandon Drake				*/
/* Copyright: Tech Media Networks 2011	*/
/****************************************/

/***************************** Review Setup **************************/

// Generates the AJAX loading indicator
function addAjaxLoader() {
    $(document).ajaxStart(function () {
        $('#tmn_tmn_ajaxBusy').show();
    }).ajaxStop(function () {
        $('#tmn_tmn_ajaxBusy').hide();
    });
}

// Tmn Generated stub for loading TmnAdsense into the
// jQuery-UI dialog
function loadPopup(name, cid) {
    //var adsense_block = document.getElementById('ss_big_image_adsense'),
    var adsense_block = document.getElementById(name),
        current_iframe = document.getElementById(name + '_scrnsht_adsense');

    if (current_iframe) {
        current_iframe.parentNode.removeChild(current_iframe);
    }

    if (typeof ss_id == 'undefined' || (typeof caption == 'string' && caption.length < 290)) {
        var new_iframe = document.createElement('iframe'),
            options = {
                n: 1,
                w: 440,
                ow: 445,
                oh: 80,
                h: 70,
                b: 0,
                ml: 0,
                mr: 0,
                cid: cid
            },
            source = '/controls/generic_adsense.html?',
            i = 0;

        new_iframe.frameBorder = 0;
        new_iframe.style.width = '445px';
        new_iframe.style.height = '80px';
        new_iframe.style.styleFloat = 'left';
        new_iframe.style.overflow = 'hidden';
        new_iframe.style.float = 'none';
        new_iframe.id = name + '_scrnsht_adsense';

        for (var key in options) {
            if (i > 0) {
                source += '&';
            }

            source += key + '=' + options[key];
            i++;
        }

        new_iframe.src = source;

        adsense_block.appendChild(new_iframe);
    } else if (caption_box) {
        caption_box.className = 'ss_big_image_caption_large';
    }
}

// Cycles to the next tab in the sequence
function nextTab(e, location) {
    _gaq.push(["_trackEvent", "article", "next", location]);
    switchTab(e, $('#tabs ul li.active').next().find('a')[0]);
    return false;
}

// Cycles to the previous tab in the sequence
function prevTab(e) {
    _gaq.push(["_trackEvent", "article", "prev", "Tab"]);
    switchTab(e, $('#tabs ul li.active').prev().find('a')[0]);
    return false;
}

// Switches article tabs
function switchTab(e, source) {
    //e.preventDefault();

    if ($(source).parent().hasClass('active') === false) {
        $('#tabs .rs_nav li').removeClass('active');
        $('#tabs .tab').hide().removeClass('active');

        $(source).parent().addClass('active');

        var tabTag = $(source).attr('href');
        $(tabTag).show().addClass('active');
    }

    reloadScripts();
}

// Initial page setup.
// Note: This needs to be called first
function pageSetup(channel) {
    playAd = null;

    addAjaxLoader();

    $('#tabs .rs_nav li:not(.compare_tab) a').click(function (e) {
        switchTab(e, this);

        return false;
    });

    var wd = (document.all && !window.opera && !window.XMLHttpRequest) ? 694 : 'auto',
        hd = wd === 694 ? 345 : 'auto'; // Fix for IE6

    $('#image_modal').dialog({
        autoOpen: false,
        show: 'easein',
        width: wd,
        closeText: '',
        resizable: false,
        beforeClose: function () {
            reloadScripts();
            this.getElementsByTagName('img')[0].src = '';
        }
    });

    $('#image_modal img').load(function () {
        $('#image_modal').dialog("open");

        throbberHide();
        reloadScripts();
    })
    .error(function () {
        throbberHide();
        reloadScripts();
    });

    $('.img_enlarge').click(function () {
        _gaq.push(["_trackEvent", "Image_Enlarge", "click", "Open Enlarged Image Popup"]);
        loadPopup('ss_big_image_adsense', channel);

        var imgPath = this.getElementsByTagName('img')[0].src.replace('thumbs/', '');

        var $this = $(this),
            pos = $this.offset(),
            e = {
                pageX: (pos.left - 20) + ($this.width() / 2),
                pageY: (pos.top - 30) + ($this.height() / 2)
            };

        throbberShow(e);

        $('#image_modal img').attr('src', imgPath);
    });

    return false;
}

// Hides the AJAX loading icon
function throbberHide() {
    $('#tmn_tmn_ajaxBusy').css({
        "top": "5px",
        "left": "5px",
        "position": "fixed"
    }).hide();
}

// Shows the AJAX loading icon relative to the click location
function throbberShow(e) {
    e = e || window.event;  // Normalize the event object

    var pageX = e.pageX || (e.clientX + document.body.scrollLeft), // check for IE position
        pageY = e.pageY || (e.clientY + document.body.scrollTop);

    $('#tmn_tmn_ajaxBusy').css({
        "top": (pageY) + "px",
        "left": (pageX) + "px",
        "position": "absolute"
    }).show();
}

// Adds the full gallery functionality to the page
function addFullGallery(jsonObject, ppid) {
    var fGallery = $('#full_gallery'),
        vSize = $(window).width() < 1100,
        closeClass = 'full_gallery_close';

    if (vSize) {
        fGallery.addClass('small');
        closeClass = 'full_gallery_close';
    }

    fGallery.gallery({
        path: '',
        thumbsPath: '/images/uploads/r70x70/',
        imgHeight: 70,
        imgWidth: 70,
        imgEvent: 'click',
        columns: (vSize ? 8 : 9),
        cssClass: 'jcarousel-skin-fgallery',
        jsonObject: jsonObject,
        fullPos: 'bottom',
        showCount: true,
        showButtons: true,
        //sponsored: true,
        //sponsorHref: 'http://google.com',
        //sponsorSrc: '../images/gallery/Sponsor.jpg',
        afterEvent: function (caller) {
            _gaq.push(["_trackEvent", "full-gallery", caller, ""]);
            reloadScripts(true);
        },
        sliderEvent: function (caller) {
            _gaq.push(["_trackEvent", "full-gallery", caller + "_slider", ""]);
            reloadScripts(true);
        }
    });

    fGallery.dialog({
        autoOpen: false,
        modal: true,
        show: 'easein',
        position: 'top',
        resizable: false,
        dialogClass: 'overlay-modal',
        closeText: "CLOSE GALLERY",
        width: (vSize ? 1020 : 1100),
        open: function () {
            var me = $(this),
                modal = $('.ui-dialog.overlay-modal').position();

            if (modal.left < 0)
                $('.ui-dialog.overlay-modal').css('left', 0);

            $('.ui-widget-overlay').toggleClass("overlay-bg").click(function () {
                me.dialog("close");
            });

            $('.ui-dialog-titlebar-close').removeClass('ui-dialog-titlebar-close').addClass(closeClass);

            reloadScripts(true);
        },
        beforeClose: function () {
            //reloadScripts();
            $('.' + closeClass).removeClass(closeClass).addClass('ui-dialog-titlebar-close');
            $('.ui-widget-overlay').toggleClass("overlay-bg");
        }
    });

    $('.overlay-modal .ui-icon-closethick').append('<img src="/images/gallery/close.png" />');

    //fGallery.dialog().parent().addClass("overlay-modal");

    $('#vfg').click(function (e) {
        //e.preventDefault();
        fGallery.dialog('open');
    });

    // Auto Center
    window.onresize = function () {
        var modal = $('.ui-dialog.overlay-modal');

        if (modal.css('display') === 'block') {
            var a = $(this).width(),
                b = modal.width(),
                c = a - b;

            modal.css('left', ((c > 0) ? (c / 2) : 0));
        }
    }
}

// Checks for the enter from the search box
function checkEnter(e, fn, passedvar) {
    var characterCode;
    if (e && e.which) {
        e = e;
        characterCode = e.which; //character code is contained in NN4's which property
    } else {
        e = event;
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }

    if (characterCode == 13) {
        fn(passedvar);
        return false;
    } else {
        return true;
    }
}

// Twitter widget setup
function nowTweeting() {
    var currentDate = new Date();
    currentDate.setDate(currentDate.getDate() - 1);
    var curyear = currentDate.getFullYear();
    var curmonth = currentDate.getMonth();
    curmonth++;

    if (curmonth < 10) {
        curmonth = '0' + curmonth;
    }

    var curday = currentDate.getDate();

    if (curday < 10) {
        curday = '0' + curday;
    }

    var ymd = curyear + '-' + curmonth + '-' + curday;
    new TWTR.Widget({
        version: 2,
        id: 'now_tweeting',
        type: 'search',
        search: 'FROM:laptopmag OR FROM:mikeprospero OR FROM:geekinchief OR FROM:akattkisson OR FROM:mspoonauer since:' + ymd,
        interval: 6000,
        title: '',
        subject: 'Now Tweeting',
        width: 'auto',
        height: 300,
        theme: {
            shell: {
                background: '#d1d1d1',
                color: '#000000'
            },
            tweets: {
                background: '#ffffff',
                color: '#000000',
                links: '#0064c7'
            }
        },
        features: {
            scrollbar: true,
            loop: true,
            live: true,
            hashtags: false,
            timestamp: false,
            avatars: true,
            toptweets: false,
            behavior: 'default'
        }
    }).render().start();
}

/***************************** MBOX Calls ****************************/
/*
var laptopMboxCounter = 0;

function laptopMboxCall(mboxName, addPageview) {
	var mboxDivId = 'mboxDynamicClick' + (++laptopMboxCounter);
	mboxCall(mboxName, mboxDivId);

	if (typeof addPageview != 'undefined' && addPageview) {
		mboxCall('laptop-templatetest-pageviews', 'mboxDynamicClick' + (++laptopMboxCounter));
	}
	return true;
}

function mboxCall(mboxName, mboxDivId) {
	try {
		var el = document.createElement('div');
		el.setAttribute('id', mboxDivId);
		document.getElementsByTagName('body')[0].appendChild(el);
		mboxDefine(mboxDivId, mboxName);
		mboxUpdate(mboxName);
	}
	catch (e) { }
}
*/

/*************************** New Nav Functions *********************************/
// Setup for the nav, also selects the current section and sub nav
function navSetup() {
    var path = (document.location.pathname).toLowerCase().replace(".aspx", "").replace("-", ""),
        parts = path.split("/"),
        len = parts.length;

    if (len > 1) {
        var loc = getSafePath(parts), a, b;

        if (loc === "ggg") {
            $('.top_nav').css('border-bottom', '1px solid #C0C0C0');
        } else if (loc === "business" || loc === "bts") {
            $('.top_nav').css('border-bottom', '1px solid #C0C0C0');
        }

        a = $("#" + loc + "_a");
        b = $("#" + loc + "_b");

        a.addClass("active");

        if (b.length > 0) {
            b.addClass("clearfix");
            a.parent().css("border-bottom", "none");

            var len = 0;

            $('#' + loc + '_b li').each(function () {
                len += $(this).outerWidth();
            })

            $('#' + loc + '_b ul').width(len + 10);
        }
    }
    
    setWidth();
}

// Sends a safe path back to the nav setup
function getSafePath(paths) {
    var path = "home",
        loc = "",
        safePaths = ["home", "laptops", "tablets", "smartphones", "review", "news", "business", "bestdeals", "ggg", "issue", "bts"];

    if (document.location.hostname.indexOf('blog.laptopmag.com') >= 0) {
        return "news";
    }

    for (var i = 0, len = paths.length; i < len; i++) {
        loc = paths[i];

        if (loc.substring(0, 3) === "ggg") {
            loc = "ggg";
        } else if (loc.substring(0, 8) === "business") {
            loc = "business";
        } else if (loc.substring(0, 3) === "bts") {
            loc = "bts";
        } else if (loc === "reviews") {
            loc = "review";
        } else if (loc === "laptop") {
            loc = "laptops";
        }

        for (var j = 0, len2 = safePaths.length; j < len2; j++) {
            if (loc == safePaths[j]) {
                path = loc;
                break;
            }
        }
    }

    return path;
}

// Fixes the nal li elements width between browsers
function setWidth() {
    var max = $('#nav ul').width() - 1,
        wid = 0,
        diff = 0,
        ct = 0,
        delta = 0;

    $('#nav ul li').each(function () {
        wid += $(this).outerWidth(true);
    });

    diff = Math.round((max - (wid)) / 4);
    delta = ((wid + (diff * 4)) - max);

    $('#nav ul li a').each(function () {
        if (ct > 6 && ct < 9) {
            var me = $(this),
                padLeft = parseInt(me.css('padding-left')),
                padRight = parseInt(me.css('padding-right'));

            me.css('padding-left', (padLeft + (diff - ((ct == 7 && delta > 0) ? delta : 0))) + "px");
            me.css('padding-right', (padRight + diff) + "px");
        }

        ct++;
    });
}

// Gets Adv Search products
function getProducts() {
    $.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=?&op=get_products', function (json) {
        var options = [];
        searchJson = json;

        options.push("<option value=''> -- All Products -- </option>");
        $('#ddlProducts').html(genSelect(searchJson.Products, options));
        getBrands();
    });
}

// Gets Adv Search sub type
function getBrands() {
    var id = getSelectedValue("ddlProducts") || "-1",
        options = [];

    options.push("<option value=''> -- All -- </option>");
    $('#ddlBrands').html(genSelect(searchJson.Sub["sub_" + id], options));
}

// Generates select options
function genSelect(data, options) {
    if (typeof data !== 'undefined') {
        for (var ct = 0, len = data.length; ct < len; ct += 1) {
            options.push("<option value='" + data[ct].value + "'>" + data[ct].name + "</option>")
        }
    }

    return options.join('');
}

// Gets the selected value from a select
function getSelectedValue(elem) {
    try {
        var e = document.getElementById(elem);
        return e.options[e.selectedIndex].value
    } catch (err) {
        return "";
    }
}

// Submit for Adv Search
function advSearch() {
    var price = document.getElementById('pricehigh').value,
        arr = [
            { "name": "pcid", "value": getSelectedValue("ddlProducts") },
            { "name": "spcid", "value": getSelectedValue("ddlBrands") },
            { "name": "pricehigh", "value": (isNaN(parseInt(price)) ? "" : price) }
        ]
    qstr = "",
        ct = 0;

    for (x in arr) {
        var val = arr[x].value;
        if (val !== "" && typeof val !== 'undefined') {
            qstr += (ct === 0 ? "?" : "&") + arr[x].name + "=" + arr[x].value;
            ct += 1;
        }
    }

    document.location = "http://www.laptopmag.com/review/advsearch.aspx" + qstr;
}

