﻿var urlParams = [];
try {
    urlParams = (function (a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p = a[i].split('=', 2);
            if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
            b[p[0]] = p[1];
        }
        return b;
    })((window.location.search.split('?'))[1].split('&'));
}
catch (err) { }

var imgCache = [];
function PreLoadImages()
{
    var args_len = arguments.length;
    for (var i = args_len; i--; ) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        imgCache.push(cacheImage);
    }
}

Page_IsValid = false;
var allowLoading = true;
var pw_timeout = 0;
window.onbeforeunload = function () {
    if (allowLoading && (pw_timeout == 0)) {
        pw_timeout = window.setTimeout(ShowPleaseWait, 1500);
    }
    else {
        allowLoading = true;
    }
}

function InitJScrollPane(content, pane) {
    var contentObj = $(content);
    var paneObj = $(pane);
    contentObj.waitForImages(function () {
        UpdateJScrollPane(contentObj, paneObj);
    });
}

function UpdateJScrollPane(contentObj, paneObj) {
    // resize content pane
    var contentHeight = contentObj.height();
    var paneHeight = paneObj.height();
    if (contentHeight < paneHeight) {
        paneObj.height(contentHeight + 10);
    }

    // init scroll pane
    paneObj.jScrollPane();
}

function CheckValidation(group) {
    // Check the page validator, this is to trap the please wait notice in IE.
    if (typeof (Page_Validators) != "undefined") {
        Page_ClientValidate(group);
        //Remove the flag to block the submit if it was raised
        Page_BlockSubmit = false;
    }

    return Page_IsValid;
}

function ShowPleaseWait() {
    $(".message_please_wait").TopCenter().show();
}

function HidePleaseWait() {
    clearTimeout(pw_timeout);
    pw_timeout = 0;
    $(".message_please_wait").hide();
}

function BlockWaitMessage() {
    if (pw_timeout)
        clearTimeout(pw_timeout);
    pw_timeout = 0;
    allowLoading = false; 
}

function ClearDefault(control)
{
	if(control.value == control.attributes.getNamedItem("DefaultText").value)
	{
		control.value = "";
	}
}

function RestoreDefault(control)
{
	if(control.value=="")
	{
		control.value=control.attributes.getNamedItem("DefaultText").value;
	}
}

function StopReturnKey(evt) 
{
    if (evt.keyCode == 13) 
    {
        evt.preventDefault();
        evt.stopImmediatePropagation();
    }
}

function AdjustTextarea(textarea) 
{
    if (textarea.scrollHeight > textarea.offsetHeight)
        textarea.style.height = textarea.scrollHeight + "px";
}

function IsProduction()
{
	var url = new String(document.location);
	if( url.indexOf("www.svb.com") == -1)
		return false;
	else
		return true;
}

function ShowStatus(sMsg) 
{
    window.status = sMsg;
    return true;
}

/*
category (required) - The name you supply for the group of objects you want to track.

action (required) - A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object. 

label (optional) - An optional string to provide additional dimensions to the event data
*/
function GoogleTrackEvent(category, action, label) 
{
    _gaq.push(['_trackEvent', category, action, label]);
}

function OpenExitLinkWindow(objHref) {
    var myWindow = window.open(objHref);
    // The popup window might have been blocked, change the main window instead.
    if (!myWindow) {
        document.location = objHref;
    }
}

function RecordExitLink(obj, category, action, label) 
{
    var delay = 0;
    try 
    {
        if (IsProduction()) 
        {
            GoogleTrackEvent(category, action, label);
            // give time for the tracking to register
            delay = 100;
        }
    }
    catch(err) {}
    setTimeout("OpenExitLinkWindow('" + obj.href + "')", delay);
}

function RecordEvent(category, action, label) {
    try 
    {
        if (IsProduction())
        {
            GoogleTrackEvent(category, action, label);
        }
    }
    catch (err) { }
}

function TrackSocial(network, socialAction) {
    try {
        if (IsProduction()) {
            _gaq.push(['_trackSocial', network, socialAction]);
        }
    }
    catch (err) { }
}

function TrackFile(label) {
    try {
        if (IsProduction()) {
            label = label.replace(/ /g, "-");
            _gaq.push(['_trackPageview', label]);
        }
    }
    catch (err) { }
}

function IsMobileAppleProduct()
{
    return ((navigator.userAgent.indexOf('iPhone') != -1) || 
            (navigator.userAgent.indexOf('iPod') != -1) || 
            (navigator.userAgent.indexOf('iPad') != -1))

}

function ShowLoading() {
    $("#svb-loading").dialog("open");
    $("#svb-loading").siblings('div.ui-dialog-titlebar').remove();
}

function EmailThisDialog() {
    jQuery(".email-this-dialog").dialog('open');
}

function MoveActionBox() {
    var h1 = $("#main_content_block h1");
    var actionbox = $("div#ActionBox");
    if (h1.length && actionbox.length) {
        h1.after(actionbox);
    }
    // need to get the box again since it's moved.
    actionbox = $("div#ActionBox");
    actionbox.show();
}

function QueueLoading() {
    window.setTimeout("ShowLoading()", 3000);
}

function SetCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function GetCookie(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;
}

function DeleteCookie(name) {
    SetCookie(name, "", -1);
}


// Detects the visitor's location using geolocation API 
function DetectGeolocation() {
    // Prompt for location only if currently scope map is derived from IP address, no session user or cookie
    if (((GetCookie("GeoLocationLatitude") != null) && (GetCookie("GeoLocationLongitude") != null)) || !navigator.geolocation) {
        return; 
    }
    
    navigator.geolocation.getCurrentPosition(DetectGeolocationSuccess, DetectGeolocationFailure);
    
    RecordEvent('Geolocation', 'Initiate');
}

// Handles successful detection of visitor's location (i.e. user permitted detection)
function DetectGeolocationSuccess(position) {
    RecordEvent('Geolocation', 'Accept');

    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    geocoder.geocode({ 'latLng': latlng }, GeocoderSuccess);
    
    function GeocoderSuccess(results, status) {
        if (status != google.maps.GeocoderStatus.OK) {
            return; 
        }
        RecordEvent('Geolocation', 'Reverse Geocode Success');
        
        var address_components = results[0]['address_components'];

        // Gather location information
        for (var i = 0; i < address_components.length; i++) {
            switch (address_components[i]['types'][0]) {
                case 'locality':
                    SetCookie("GeoLocationCity", address_components[i]['long_name'], 1);
                    break;
                case 'administrative_area_level_1':
                    SetCookie("GeoLocationState", address_components[i]['short_name'], 1);
                    break;
                case 'country':
                    SetCookie("GeoLocationCountry", address_components[i]['long_name'], 1);
                    break;
            }
        }
        
        SetCookie("GeoLocationLatitude", results[0]['geometry']['location'].lat(), 1);
        SetCookie("GeoLocationLongitude", results[0]['geometry']['location'].lng(), 1);

        // refresh page using new location
        document.location.href = document.location.href;
    }
}

//Handles unsuccessful detection of visitor's location (i.e. user declined permission for detection)
function DetectGeolocationFailure() {
    RecordEvent('Geolocation', 'Deny');
}

function SupportsCanvas() {
    return !!document.createElement('canvas').getContext;
}

// Grayscale w canvas method
function Grayscale(src) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var imgObj = new Image();
    imgObj.src = src;
    canvas.width = imgObj.width;
    canvas.height = imgObj.height;
    ctx.drawImage(imgObj, 0, 0);
    var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
    for (var y = 0; y < imgPixels.height; y++) {
        for (var x = 0; x < imgPixels.width; x++) {
            var i = (y * 4) * imgPixels.width + x * 4;
            var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
            imgPixels.data[i] = avg;
            imgPixels.data[i + 1] = avg;
            imgPixels.data[i + 2] = avg;
        }
    }
    ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
    return canvas.toDataURL();
}

function ProcessGrayImages() {
    $('.grayimage').one('load', function () {
        if (SupportsCanvas()) {
            var el = $(this);
            var width = this.width;
            var height = this.height;
            el.css({ "position": "absolute" }).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({ "position": "absolute", "z-index": "998", "opacity": "0" }).insertBefore(el).queue(function () {
                var el = $(this);
                el.parent().css({ "width": width, "height": height });
                el.dequeue();
            });
            this.src = Grayscale(this.src);
        }
    }).each(function () {
        if (this.complete)
            $(this).load();
    });
}



