var $j = jQuery.noConflict();

$j(document).ready(function () {
	var links = $j("a");
	$j.each(links, function (i, val) {
		var url = val.toString().toLowerCase();		

		if ($j(this).hasClass("fancyPopUp")) {
			var fancy_url = $j(this).attr("href");
			$j(this).attr("href", "#");
			jQuery(this).fancybox({
				'padding': 0,
				'centerOnScroll': true,
				'autoScale': true,
				'scrolling': 'none',
				titleShow: false,
				'href': fancy_url
			});
		}
		
		if (url.indexOf(".ashx") > -1 || url.indexOf("documentviewer") > -1) {
			//Adding tracking for media library and publications
			$j(this).attr("onclick", "javascript:_gaq.push(['_trackPageview','" + url + "']);");
		}

		if (url.indexOf("sitecore/content/global/product") > -1) {

			var replace = "";
			if (location.href.indexOf("sitecore/content/") > -1) {
				var tempUrl = location.href.substring(location.href.indexOf("sitecore/content/"));
				tempUrl = tempUrl.replace("sitecore/content/", "");
				tempUrl = tempUrl.substring(0, tempUrl.indexOf("/"));
				replace = "sitecore/content/" + tempUrl + "/";
			}
			$j(this).attr('href', url.replace("sitecore/content/global/", replace));
		}
	});


	jQuery(".fancyBox_flash").click(function () {
		jQuery.fancybox({
			'padding': 0,
			'autoScale': false,
			'transitionIn': 'none',
			'transitionOut': 'none',
			'title': this.title,
			'width': 1024,
			'height': 768,
			'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type': 'swf',
			'swf': {
				'wmode': 'transparent',
				'allowfullscreen': 'true'
			}
		});
		return false;
	});
});

var flashVersion = "10.0.0";

var scDatabase;
var scLanguage;

function initVars(db, lang) {
    scDatabase = db;
    scLanguage = lang;
}

function TestFlash() {
    var arrVersion = flashVersion.split(".");

    if (arrVersion[0] > swfobject.getFlashPlayerVersion().major) {
        location.replace("/noflash.htm");
    }
}

function GetHostName() {
    var hostname = window.location.hostname;
    if (window.location.port != "")
        hostname += ":" + window.location.port;
    return hostname;
}

function LoadHtml(url) {
    $j.ajax({
        type: "GET",
        url: url,
        success: function (response) {
            $j('#div_Content').html(response);
        }
    });
}

function LoadPushFlash(url, tabfield, link, target, header) {
    var flashvars = {};
    flashvars.link = link;
    flashvars.target = target;
    flashvars.header = header;
    var params = {};
    params.menu = "false";
    params.wmode = "transparent";
    var attributes = {};
    swfobject.embedSWF(url, tabfield, "326", "216", flashVersion, "/-/media/Files/Flash/swfobject/expressInstall.ashx", flashvars, params, attributes);
}

function changeImage(element, source) {
    document.getElementById(element).src = source;
}

function ClearTextBox() {
    document.getElementById("TextBoxSearch").value = "";
}

function SubmitSearch(e, id, url, view) {
    if (!IsSearchable(id)) {
        return false;
    }
    if (IsEnter(e)) {
        Search(id, url, view);
        return false;
    }
    return true;
}

function SubmitSearchPublication(e, language) {
    if (IsEnter(e)) {
        SearchPublication(language);
        return false;
    }
    return true;
}


function IsEnter(e) {
    var keynum;

    if (window.event) // IE
    {
        keynum = e.keyCode
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which
    }
    return keynum == 13;
}

//noinspection FunctionWithInconsistentReturnsJS
function Search(id, url, view) {
    var query = document.getElementById(id);

    if (query.value == "")
        return false;

    if (!IsSearchable(id))
        return false;

    url += "?page=1";
    if (query != null && query.value != "") {
        url += "&query=" + Url.encode(query.value);
    }
    if (view != null && view != "") {
        url += "&view=" + view;
    }
    window.location.href = url;
}

function IsSearchable(id) {
    //skip testing if not TextBoxSearch
    if (id != 'TextBoxSearch')
        return true;

    var query = document.getElementById(id);
    var hiddenquery = document.getElementById('hidden_seach_Criteria');

    if (query.value.toLowerCase() == hiddenquery.value.toLowerCase()) {
        $j('#' + id).focus();
        $j('#' + id).val("");
        return false;
    }
    return true;
}

function SearchPublication(language) {
    var query = document.getElementById('query');
    var queryProduct = document.getElementById('container_0_content_0_ddlProducts');
    var queryType = document.getElementById('container_0_content_0_ddlTypes');
    var queryLanguage = document.getElementById('container_0_content_0_ddlLanguages');
    var url = "/" + language + "/Publications?page=1";

    if (query != null && query.value != "") {
        url += "&query=" + Url.encode(query.value);
    }

    url += "&queryProduct=" + queryProduct.value;
    url += "&queryType=" + queryType.value;
    url += "&queryLanguage=" + queryLanguage.value;

    window.location.href = url;
}

var Url = {

    // public method for url encoding
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c1;
        var c = c1 = c2 = 0;

        var c3;
        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else var c2;
            if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
};

/*********************/
/* SubMenu functions */
/*********************/
var subMenu = new Array();
var resetSubMenuTimeOut;

function GetSubMenu(shortID) {
	
    ClearSubMenuTimeOut();
    var subMenuStr = "";
    var strClass;
    var currentMenu;
    var menu;
	
    if (subMenu[shortID] != null && subMenu[shortID].length > 0) {
        menu = subMenu[shortID].split("|");
        for (var i = 0; i < menu.length; i++) {
            if (menu[i].length > 0) {
                currentMenu = menu[i].split("_");
                strClass = "";
                if (currentMenu.length == 3) {
                    strClass = "class='SubMenuActive'";
                }
                subMenuStr += "<a href='" + currentMenu[0] + "' " + strClass + ">" + currentMenu[1] + "</a>";

                if (i < menu.length - 1)
                    subMenuStr += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            }
        }
    }

    document.getElementById("submenu").innerHTML = subMenuStr;
}

function ManageSubMenu(shortID) {
    ClearSubMenuTimeOut();
    resetSubMenuTimeOut = setTimeout("GetSubMenu('" + shortID + "')", 500);
}

function ResetSubMenu(shortID) {
    ClearSubMenuTimeOut();
    resetSubMenuTimeOut = setTimeout("GetSubMenu('" + shortID + "')", 1000);
}

function ClearSubMenuTimeOut() {
    clearTimeout(resetSubMenuTimeOut);
}

/*****************
* TABS functions *
*****************/
function switchTabStyle(tabID, state) {
    if (state == "over") {
        document.getElementById("TabLeft" + tabID).src = "http://www.widex.pro/-/media/WidexShared/design/tab_left_over.ashx";
        document.getElementById("TabTile" + tabID).className = "page_Tab_over";
        document.getElementById("TabRight" + tabID).src = "http://www.widex.pro/-/media/WidexShared/design/tab_right_over.ashx";
    } else if (state == "out") {
        document.getElementById("TabLeft" + tabID).src = "http://www.widex.pro/-/media/WidexShared/design/tab_left.ashx";
        document.getElementById("TabTile" + tabID).className = "page_Tab";
        document.getElementById("TabRight" + tabID).src = "http://www.widex.pro/-/media/WidexShared/design/tab_right.ashx";
    }
}

$j(document).ready(function () {
    $j('a#linkTextSize').click(function () {
        ChangeFontsize();
    });

    $j('img.changeFontSize').click(function () {
        ChangeFontsize();
    });

});

function ChangeFontsize() {

    fontSizeSmall = !fontSizeSmall;
    var url = "/Views/Ajax/FontSize.aspx?fontsize=true";
    if (!fontSizeSmall) {
        url = "/Views/Ajax/FontSize.aspx?fontsize=false";
    }
    SetFontSize();
    $j.ajax({
        type: "POST",
        url: "/Views/Ajax/FontSize.aspx",
        data: "fontsize=" + fontSizeSmall
    });
}

function SetFontSize() {
    var fontSizeText1 = 12;
    var fontSizeText2 = 14;
    var src = '/-/media/WidexShared/design/font_button_small.ashx';
    if (!fontSizeSmall) {
        fontSizeText1 = 14;
        fontSizeText2 = 16;
        src = '/-/media/WidexShared/design/font_button_large.ashx';
    }
    $j('.page_general,.page_TextColumn_first, .page_TextColumn_second, h2').css('font-size', fontSizeText1);
    $j('#downloadPage').css('font-size', fontSizeText1);
    $j('.summary').css('font-size', fontSizeText2);
    $j('img.changeFontSize').attr('src', src);

}

function closePopup(id) {
    var e = document.getElementById(id);
    e.style.display = 'none';
}
function openPopup(id) {
    var e = document.getElementById(id);
    e.style.display = 'block';
}
function makeActive(e) {
    e.className = "active";
}
function removeActive(e) {
    e.className = "";
}

function loadNewsRoom(url) {
    location.href = url + "?newstype=" + $j("#newstype").val() + "&newsyear=" + $j("#newsyear").val();
}

function LoadSeries(url1, url2, url3, seriesName, modelName, agentId) {
    $j.ajax({
        type: "GET",
        url: url1 + "?ajax=1&model=" + seriesName,
        success: function (response) {
            $j("#selectSeries").html(response);
        }
    });

    $j.ajax({
        type: "GET",
        url: url2,
        success: function (response) {
            $j('#selectModel #list').html(response);
        }
    });
    LoadModel(url3, modelName, false,agentId);
}

function LoadModel(url, modelName, changeFocus,agentId) {
    if (changeFocus) {
        $j("#list .active").removeClass("active");
        $j("#list #link_" + modelName).addClass("active");

    }
    $j.ajax({
        type: "GET",
        url: url,
        success: function (response) {
            $j('#coloursAndModelsText #content').html(response);
        }
    });
    LoadFlash(modelName,agentId);
}

function LoadFlash(modelName, agentId) {
    var flmov = document.getElementById("ColorsAndModels");
    flmov.changeModel("http://" + GetHostName() + "/xml/ModelData.xml?sc_lang=" + scLanguage + "&sc_database=" + scDatabase + "&name=" + modelName + "&agentid="+ agentId);
}

function chooseCountry() {
    window.open($j("#ChooseCountry").val());
}

function changeDownloadType(url) {
    var type = $j("#container_0_content_0_ddlTypes").val();
    url += "?queryType=" + type;
    location.href = url;
}
function searchDownloads(url) {
    var type = $j("#container_0_content_0_ddlTypes").val();
    var product = $j("#container_0_content_0_ddlProducts").val();
    var language = $j("#container_0_content_0_ddlLanguages").val();
    url += "?queryType=" + type;
    
    if (product != "") {
        url += "&queryProduct=" + product;
    }

    if (language != "") {
        url += "&queryLanguage=" + language;
    }
    location.href = url;
}


function openFlashWindow(url, width, height) {
    var windowUrl = 'http://static2.widex.com/Views/FilePage.aspx?url=' + url + '&width=' + width + '&height=' + height;
    openWindowType(windowUrl, 'flash', width, height);
}

function openImageWindow(url, width, height) {
    var windowUrl = 'http://static2.widex.com/Views/FilePage.aspx?url=' + url + '&width=' + width + '&height=' + height;
    openWindowType(windowUrl, 'image', width, height);
}

function openWindowType(url, fileType, width, height) {
    var newwindow = window.open(url + '&' + fileType + '=true', 'name', 'height=' + height + ',width=' + width + '');
    if (window.focus) {
        newwindow.focus();
    }
}

function openWindow(url, width, height) {
    var newwindow = window.open(url, 'name', 'height=' + height + ',width=' + width + '');
    if (window.focus) {
        newwindow.focus();
    }
}

function contactShowRegion(region) {
    $j('#countries_table tbody tr').hide();
    $j('#countries_table tbody tr.' + region).fadeIn(100);
}
