﻿function Common_Search(o)
{
    var query = o.value;
    var url = Common_Search_Url + '&q=' + Common_UrlEncode(query);
    document.location.href = url;
}

function Common_Search_KeyPress(o, e)
{
    if (Common_EnterPressed(o, e))
    {
        Common_Search(o);
        return false;
    }
    else
    {
        return true;
    }
}

function Common_AddClickSource(a, source)
{
    if (a.href.indexOf("source=") == -1)
    {
        var query = a.href.indexOf("?") > -1 ? "&" : "?";
        a.href += query + "source=" + source;
    }
}

function Common_TrackEvent(category, action)
{
    try
    {
        GA_TrackEvent(category, action);
    }
    catch (err)
    {
    }
}

function Common_EndRequest(sender, args)
{
    if (args.get_error() != undefined)
    {
        alert(Common_Ajax_Error_Popup);
        args.set_errorHandled(true);
    }
}

function Common_EnterPressed(o, e)
{
    var keycode;
    if (window.event)
    {
        keycode = window.event.keyCode;
    }
    else if (e)
    {
        keycode = e.which;
    }
    else
    {
        return false;
    }
    if (keycode == 13)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function Common_UrlEncode(input)
{
    var output = '';
    var x = 0;
    input = input.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < input.length)
    {
        var match = regex.exec(input.substr(x));
        if (match != null && match.length > 1 && match[1] != '')
        {
            output += match[1];
            x += match[1].length;
        } else
        {
            if (input[x] == ' ')
                output += '+';
            else
            {
                var charCode = input.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}

function Common_CancelBubble(e)
{
    if (window.event)
    {
        window.event.cancelBubble = true;
    }
    else if (e)
    {
        e.cancelBubble = true;
    }
}

function Common_LoadingMessage_Big(message)
{
    var url = '<%=ImageLibrary.GetCoreImageUrl("ajax-loader.gif")%>';
    return '<div class="loading-message"><div><img src="' + url + 'align="absmiddle" />' + message + '</div></div>';
}

function Common_LoadMap(controlID, latitude, longitude, title, description)
{

    // Load map
    var map = new VEMap(controlID);
    map.SetDashboardSize(VEDashboardSize.Small);
    map.LoadMap(new VELatLong(latitude, longitude), 15, 'r', false);
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);

    // Add pin
    var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(latitude, longitude));
    pin.SetTitle(title);
    pin.SetDescription(description);
    map.AddShape(pin);

}

function Common_Pws(u, a, v, p)
{
    var src = '/pws.gif?u=' + u + '&a=' + a + '&v=' + v + '&p=' + p;
    Common_PwsImage(src);
}

function Common_GC(i, l)
{
    var src = 'http://www.googleadservices.com/pagead/conversion/' + i + '/?value=1.0&guid=ON&script=0&label=' + l;
    Common_PwsImage(src);
}

function Common_PwsImage(src)
{
    var r = Math.floor(Math.random() * 9999999999);
    var image = new Image(1, 1);
    image.src = src + '&r=' + r;
    image.onload = function () { return; };
}

function Common_ValidateCurrencyWithSymbol(value)
{
    var re = new RegExp(__reCurrencyWithSymbol);
    return re.test(value);
}

function Common_AddTooltip(imageID, htmlID)
{

    if (wo$(imageID) != null)
    {
        if (htmlID == null || htmlID == undefined || htmlID == '')
        {
            wo$(imageID).tooltip(
            {
                showURL: false,
                track: true,
                delay: 0
            });
        }
        else
        {
            wo$(imageID).tooltip(
            {
                bodyHandler: function ()
                {
                    return (wo$(htmlID).html());
                },
                showURL: false,
                track: true,
                delay: 0
            });
        }
    }
}

function Common_CompareChecked(id)
{
    return wo$('#' + id + ' input:checkbox:checked');
}

function Common_CompareClick(id, topID, cb, e, tv, speed)
{
    Common_CancelBubble(e);
    var count = Common_CompareChecked(id).length;

    if (tv)
    {
        if (count == 0)
        {
            wo$('#' + topID).hide(speed);
        }
        else
        {
            wo$('#' + topID).show(speed);
        }
    }

    if (count > 3)
    {
        cb.checked = false;
        alert('You can only select a maximum of 3 items to compare side-by-side');
    }

}

function Common_Compare(id)
{
    var count = Common_CompareChecked(id).length;
    if (count < 2)
    {
        alert('Please select at least 2 items to compare side-by-side');
        return false;
    }
    else
    {
        var urls = [];
        Common_CompareChecked(id).each(function ()
        {
            urls.push(wo$(this).val());
        });
        var url = __compareBase + '/' + urls.join('-compared-');
        if (__compareQuery != '')
        {
            url += '?' + __compareQuery;
        }
        window.setTimeout(function () { location.href = url; }, 200)
        return false;
    }
}

function Common_AddToggle(toggleID, targetID)
{
    wo$(toggleID).click(function ()
    {
        wo$(targetID).toggle();
        var toggle = wo$(toggleID);
        if (toggle.is('.icon-maximise'))
        {
            toggle.removeClass('icon-maximise');
            toggle.addClass('icon-minimise');
        }
        else
        {
            toggle.removeClass('icon-minimise');
            toggle.addClass('icon-maximise');
        }
    });
}

var panes = new Array();

function setupPanes(containerId, defaultTabId)
{
    panes[containerId] = new Array();
    var maxHeight = 0; var maxWidth = 0;
    var container = document.getElementById(containerId);
    var paneContainer = document.getElementById(containerId + "-panes");
    var paneList = paneContainer.childNodes;
    for (var i = 0; i < paneList.length; i++)
    {
        var pane = paneList[i];
        if (pane.nodeType != 1 || pane.tagName != "DIV") continue;
        if (pane.offsetHeight > maxHeight) maxHeight = pane.offsetHeight;
        if (pane.offsetWidth > maxWidth) maxWidth = pane.offsetWidth;
        panes[containerId][pane.id] = pane;
    }
}

function showPane(paneId, activeTab)
{
    for (var con in panes)
    {
        activeTab.blur();
        activeTab.className = "tab-active";
        if (panes[con][paneId] != null)
        {
            var pane = document.getElementById(paneId);
            pane.style.display = "block";
            var container = document.getElementById(con);
            var tabs = container.getElementsByTagName("ul")[0];
            var tabList = tabs.getElementsByTagName("a")
            for (var i = 0; i < tabList.length; i++)
            {
                var tab = tabList[i];
                if (tab != activeTab) tab.className = "tab-disabled";
            }
            for (var i in panes[con])
            {
                var pane = panes[con][i];
                if (pane == undefined || pane.tagName != "DIV") continue;
                if (pane.id == paneId) continue;
                pane.style.display = "none"
            }
        }
    }
    return false;
}

function Common_MegaHoverOver()
{
    if (wo$.validationEngine)
    {
        wo$('form').validationEngine('hideAll');
    }
    if (wo$.browser.msie && parseInt(wo$.browser.version) == 6)
    {
        wo$('select').css("visibility", "hidden");
        wo$(this).find(".nav-wo-sub").show();
    }
    else
    {
        wo$(this).find(".nav-wo-sub").stop().fadeTo('fast', 1).show();
    }
}

function Common_MegaHoverOut()
{
    if (wo$.browser.msie && parseInt(wo$.browser.version) == 6)
    {
        wo$(this).find(".nav-wo-sub").hide();
        wo$('select').css("visibility", "visible");
    }
    else
    {
        wo$(this).find(".nav-wo-sub").stop().fadeTo('fast', 0, function () { wo$(this).hide(); });
    }
}

function Common_SliderTabs(headerID, bodyID)
{

    //Get the height of the first item
    wo$(bodyID + ' #mask').css({ 'height': wo$(bodyID + ' #panel-1').height() });

    //Calculate the total width - sum of all sub-panels width
    //Width is generated according to the width of #mask * total of sub-panels
    wo$(bodyID + ' #panel').width(parseInt(wo$(bodyID + ' #mask').width() * wo$(bodyID + ' #panel div').length));

    //Set the sub-panel width according to the #mask width (width of #mask and sub-panel must be same)
    wo$(bodyID + ' #panel div').css('visibility', 'visible').width(wo$(bodyID + ' #mask').width());

    //Get all the links with rel as panel
    wo$(headerID + ' a[rel=panel]').click(function ()
    {

        //Get the height of the sub-panel
        var panelheight = wo$(wo$(this).attr('href')).height();

        //Set class for the selected item
        wo$(headerID + ' a[rel=panel]').removeClass('tab-active');
        wo$(this).addClass('tab-active');

        //Resize the height
        wo$(bodyID + ' #mask').animate({ 'height': panelheight }, { queue: false, duration: 500 });

        //Scroll to the correct panel, the panel id is grabbed from the href attribute of the anchor
        wo$(bodyID + ' #mask').scrollTo(wo$(this).attr('href'), 800);

        //Discard the link default behavior
        return false;
    });
}

function Common_AddHover(id, index, left, top)
{
    wo$('#' + id + '_t' + index).tooltip(
        {
            showURL: false,
            delay: 300,
            track: true,
            positionLeft: true,
            left: left,
            top: top,
            bodyHandler: function ()
            {
                return wo$('#' + id + '_tp' + index).html();
            }
        });
}

function Common_LoadAdContent(content, target)
{
    debugger;
    if (target && content && content.trim() != '')
    {
        target.innerHTML = content;
        target.style.display = '';
    }
}

function Common_CTA(addScrollHandler)
{
    var height = wo$('#main-wo').height() - wo$('#sidebar-wo').height() - 30;
    wo$('#sliding-box-wrap').css('height', height);
    if (addScrollHandler)
    {
        wo$(window).scroll(Common_CTA_Scroll);
        Common_CTA_Scroll();
    }
}

function Common_CTA_Scroll()
{
    var box = wo$('#sliding-box');
    var wrap = wo$('#sliding-box-wrap');
    var start = wrap.offset().top - 20;
    var end = wrap.offset().top + wrap.height() - box.height() - 20;

    var y = wo$(this).scrollTop();
    if (y >= end)
    {
        if (box.hasClass('fixed-bottom') == false)
        {
            box.removeClass('fixed');
            box.addClass('fixed-bottom');
        }
    }
    else if (y >= start)
    {
        if (box.hasClass('fixed') == false)
        {
            box.removeClass('fixed-bottom');
            box.addClass('fixed');
            try
            {
                box.fadeTo('medium', 1);
            }
            catch (err)
            {
                box.css({ opacity: 1 });
            }
        }
    }
    else
    {
        box.removeClass('fixed-bottom');
        box.removeClass('fixed');
    }
}

function Common_IFrameLinks()
{
    wo$('.iframe-link').fancybox(
    {
        'type': 'iframe'
        , 'width': wo$(window).width() > 900 ? 900 : wo$(window).width()
        , 'height': wo$(window).height() > 800 ? 800 : wo$(window).height()
    });
}

function Common_IFrameLinksElement(id)
{
    wo$('#' + id + ' .iframe-link').fancybox(
    {
        'type': 'iframe'
        , 'width': wo$(window).width() > 900 ? 900 : wo$(window).width()
        , 'height': wo$(window).height() > 800 ? 800 : wo$(window).height()
    });
}

function Common_ShowAd(ads, target)
{

    try
    {
        var pegs = new Array();
        var max = 0;
        for (var x = 0; x < ads.length; x++)
        {
            if (ads[x].r == 0)
            {
                pegs[x] = 0;
            }
            else
            {
                max += ads[x].r;
                pegs[x] = max;
            }
        }

        var random = Math.ceil(Math.random() * max);
        for (var x = 0; x < pegs.length; x++)
        {
            if (random <= pegs[x])
            {
                wo$('#' + target).html(ads[x].c).show();
                break;
            }
        }

    }

    catch (err)
    {
    }

}


