/// <reference path="jquery-1.3.2.js"/>
/// <reference path="jquery/jquery-1.3.2-vsdoc2.js"/>
/// <reference path="ui/ui.core.js"/>
/// <reference path="ui/ui.dialog.js"/>
/// <reference path="ui/ui.draggable.js"/>
/// <reference path="ui/ui.resizable.js"/>
/// <reference path="ui/ui.accordion.js"/>

// ---------------
// Adapts the height of the news listing on the start page.
// ---------------
function adaptStartPageDivs() {
    var leftDiv = document.getElementById('StartPageLeftDiv');
    var rightDiv = document.getElementById('StartPageRightDiv');
    var newsDiv = document.getElementById('StartPageNewsDiv');

    if (leftDiv && rightDiv && newsDiv) {
        if (leftDiv.clientHeight > rightDiv.clientHeight) {
            var topHeaderMargin = 29 + 17; // 29 is header height and 17 is padding on the div
            newsDiv.style.height = (leftDiv.clientHeight - topHeaderMargin) + 'px';
        }
    }
}

// ---------------
// Toggles visibility of the specified element.
// ---------------
function toggleVisibility(elemId) {
    var elem = document.getElementById(elemId);

    if (elem) {
        if (elem.style.display == 'none') {
            elem.style.display = 'block';
        }
        else {
            elem.style.display = 'none';
        }
    }
}

// ------------------------------------------------------------
// This function will fire a click event on the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return fireClickOnEnter(event, 'IdOfControlToFireClickOn');">
// ------------------------------------------------------------
function fireClickOnEnter(evt, controlId) {
    var control = document.getElementById(controlId);
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> fire click-event on the control
    if (control && (keyCode == 13)) {
        control.focus();
        control.click();
        return false;
    }
    else {
        return true;
    }
}

// ------------------------------------------------------------
// This function will fire a postbackon the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return postbackOnEnter(event, 'IdOfControlToFirePostbackOn');">
// ------------------------------------------------------------
function postbackOnEnter(evt, controlId) {
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> do a postback
    if (keyCode == 13) {
        __doPostBack(controlId, '');
        return false;
    }
    else {
        return true;
    }
}

// ------------------------------------------------------------
// Returns the x coordinate of the specified object
// ------------------------------------------------------------
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientLeft) {
        curleft += obj.clientLeft;
    }
    return curleft;
}

// ------------------------------------------------------------
// Encrypts the specfied string using the xor algorithm.
// The encrypted string can be decrypted by calling this method again
// with the same key.
// ------------------------------------------------------------
function xorEncryptString(str, key) {
    var result = '';
    for (var i = 0; i < str.length; i++) {
        result += String.fromCharCode(key ^ str.charCodeAt(i));
    }
    return result;
}

// ------------------------------------------------------------
// Returns the y coordinate of the specified object
// ------------------------------------------------------------
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientTop) {
        curtop += obj.clientTop;
    }
    return curtop;
}

// ------------------------------------------------------------
// Builds an html-page for printing
// ------------------------------------------------------------
function printPage(pagename, appRoot) {
    if (!window.print) {
        window.status = 'No print';
        return;
    }

    // Get the main content area and other stuff we need
    var contentdiv = document.getElementById('printarea');

    if (contentdiv) {
        var contentHtml = '<div style="width: 100%; padding: 30px 20px 0px 20px;">';
        contentHtml += '<img src="/Templates/Styles/Images/exp_printmall_logo.gif" border="0" alt="Exportr&aring;det" style="margin-bottom: 30px;" />';
        contentHtml += contentdiv.innerHTML + '</div>';

        var beginHtml =
		      '<html>' +
			  '<head>' +
			  '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' +
			  '<link rel="stylesheet" type="text/css" href="' + appRoot + 'Templates/Styles/CSS/all.css">' +
			  '<title>Exportr&aring;det - ' + pagename + '</title>' +
			  '<style type="text/css">' +
			    '.printExclude { visibility: hidden; position: absolute; top: 0px; height: 0px; }' +
			    'ul.tools-small { visibility: hidden; position: absolute; top: 0px; height: 0px; }' +
			    '.info { width: 100%; }' +
			    '.info-wide { width: 100%; }' +
			  '</style>' +
			  '</head>' +
			  '<body style="margin: 0px; background-image: none; background-color: #fff;">';

        var endHtml = '</body></html>';

        var printWin = window.open('about:blank', '', 'width=700,height=600,scrollbars=yes,toolbar=yes');
        printWin.document.open();
        printWin.document.write(beginHtml +
		                        contentHtml +
		                        endHtml);

        printWin.document.close();
        printWin.print();
        printWin.close();
    }
}

// ------------------------------------------------------------
//	Opens a new window that will login to SchoolSoft
// ------------------------------------------------------------
function schoolSoftLogin() {
    var usertypeSelect = document.getElementById('SchoolSoftUsertype');
    var usernameTextbox = document.getElementById('SchoolSoftUsername');
    var passwordTextbox = document.getElementById('SchoolSoftPassword');

    if (usertypeSelect && usernameTextbox && passwordTextbox) {
        var usertype = usertypeSelect.options[usertypeSelect.selectedIndex].value;
        var username = usernameTextbox.value;
        var password = xorEncryptString(passwordTextbox.value, 31);
        var url = gAppRoot + 'Pages/SchoolSoftLogin.aspx?usertype=' + usertype +
			'&username=' + encodeURIComponent(username) +
			'&password=' + encodeURIComponent(password);

        var win = window.open(url, 'SchoolSoftWindow');
        win.focus();
    }
}

// ------------------------------------------------------------
// Opens the Tipsa-window
// ------------------------------------------------------------
function openTipPage(pageId) {
    var width = 340;
    var height = 540;
    var left = (screen.width - width) / 2;
    var top = ((screen.height - height) / 2) - 30;

    var win = window.open(gAppRoot + 'Pages/Edit/SendTip.aspx?pageid=' + pageId, 'TipWindow', 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + ',location=no,scrollbars=yes,menubar=no,toolbar=no,resizable=no,status=yes');
    win.focus();
}

// ---------------
// Displays the specified image. 
// Used by the image browser function.
// ---------------
function imageBrowserShowImage(index) {
    // Roll over index if it's too high or low
    if (index < 0) {
        index = gImageBrowserUrls.length - 1;
    }
    else if (index >= gImageBrowserUrls.length) {
        index = 0;
    }

    // Change image on the image tag
    var imageTag = document.getElementById(gImageBrowserTagId);
    if (imageTag) {
        imageTag.src = gImageBrowserUrls[index];
        imageTag.alt = gImageBrowserDescriptions[index];
        gImageBrowserCurrentIndex = index;
    }

    // Change the image description
    var divText = document.getElementById('ImageBrowserDescription');
    if (divText) {
        divText.innerHTML = gImageBrowserDescriptions[index];
    }

    // Change the current image index label
    var spanTag = document.getElementById('ImageBrowserCurrentIndex');
    if (spanTag) {
        spanTag.innerHTML = (index + 1);
    }
}
function doClick(buttonName, e) {
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;

    if (window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if (key == 13) {
        //Get the button the user wants to have clicked
        var btn = document.getElementById(buttonName);
        if (btn != null) { //If we find the button click it
            btn.click();
            event.keyCode = 0
        }
    }
}


var getFFVersion = navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight = parseFloat(getFFVersion) >= 0.1 ? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeIframe(frameid) {

    var currentfr = document.getElementById(frameid);
    if (currentfr && !window.opera) {
        currentfr.style.display = "block";

        if (currentfr.contentDocument && currentfr.contentDocument.body && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
            currentfr.height = currentfr.contentDocument.body.offsetHeight + FFextraHeight;
        else if (currentfr.Document && currentfr.Document.body && currentfr.Document.body.scrollHeight) //ie5+ syntax
        {
            if (currentfr.Document.body.scrollHeight == 35)	//Avantime fix for hiding iframe if empty.
                currentfr.style.display = "none";
            else
                currentfr.height = currentfr.Document.body.scrollHeight;
        }
        if (currentfr.addEventListener)
            currentfr.addEventListener("load", readjustIframe, false);
        else if (currentfr.attachEvent) {
            currentfr.detachEvent("onload", readjustIframe);
            currentfr.attachEvent("onload", readjustIframe);
        }

    }
}


function readjustIframe(loadevt) {
    var crossevt = (window.event) ? event : loadevt
    var iframeroot = (crossevt.currentTarget) ? crossevt.currentTarget : crossevt.srcElement
    if (iframeroot)
        resizeIframe(iframeroot.id);
}

//----------------
// Shows a YouTube video
//----------------
function showYoutubeVideo(url, insertIntoID, title, autoplay, width, height) {
    var swfObject;

    if (autoplay == true)
        autoplay = "&autoplay=1;"
    else
        autoplay = "";

    swfObject = new SWFObject(url + "&enablejsapi=1&playerapiid=ytplayer&color1=0x006699&color2=0x54abd6&rel=0" + autoplay, "ytapiplayer", width, height, "8", "#FFFFFF");
    swfObject.addParam("wmode", "transparent");
    swfObject.write(insertIntoID);

    // Send to SiteCatalyst
    SendVideoToSC(title);
}

//---------------
// Send YouTube data to SiteCatalyst
//---------------
function SendVideoToSC(videoTitle) {
    var t = s_gi('exportradetswedishtrade');
    if (t != null) {
        t.linkTrackVars = 'prop10';
        t.linkTrackEvents = 'None';
        t.prop10 = videoTitle;
        t.tl('YouTube: ' + videoTitle, 'o', 'YouTube');
    }
}

//---------------
// Send data to SiteCatalyst
//---------------
function SendToSiteCatalystProp14(projectTitle) {
    var t = s_gi('exportradetswedishtrade');
    if (t != null) {
        t.linkTrackVars = 'prop14';
        t.linkTrackEvents = 'None';
        t.prop14 = projectTitle;
        t.tl(projectTitle, 'o', 'ProjectTitle');
    }
}

// ---------------
// Hides all windowed controls in browsers that
// can't display layers on top of them.
// ---------------
function hideWindowedControls() {
    if (($.browser.msie == true) && ($.browser.version < 7)) {
        // Hides all listboxes
        for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
            document.getElementsByTagName('select')[i].style.visibility = 'hidden';
        }
    }
}

// ---------------
// Shows all windowed controls.
// ---------------
function showWindowedControls() {
    if (($.browser.msie == true) && ($.browser.version < 7)) {
        // Show all listboxes
        for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
            document.getElementsByTagName('select')[i].style.visibility = 'visible';
        }
    }
}

// ----------------
// AJAX Quick Search
// ----------------
$(document).ready(function() {
    $(document).bind('click', function(e) {
        var $clicked = $(e.target);

        if (!($clicked.is('#quick-search') || $clicked.parents().is('#quick-search'))) {
            $('#quick-search').hide();
        }
    });
    $('#quick-search').prev().bind('keyup', function(e) {
        if (e.keyCode == 38) {
            if (ajaxqs.is(':visible')) {
                var items = $('div', ajaxqs);
                if (qscursor > -1) {
                    $(items[qscursor]).find('a:first').removeClass('active');
                    $(items[--qscursor]).find('a:first').addClass('active');
                }
                $('#qs-nfo', ajaxqs).html((qscursor > -1) ? 'Tryck Enter f&#246r att <span>f&#246lja l&#228nk</span>' : 'Tryck Enter f&#246r att <span>s&#246ka</span>');
            }
        }
        else if (e.keyCode == 40) {
            if (ajaxqs.is(':visible')) {
                var items = $('div', ajaxqs);
                if ((qscursor + 2) < items.length) {
                    if (qscursor != -1) $(items[qscursor]).find('a:first').removeClass('active');
                    $(items[++qscursor]).find('a:first').addClass('active');
                    $('#qs-nfo', ajaxqs).html('Tryck Enter f&#246r att <span>f&#246lja l&#228nk</span>');
                }
            }
        }
        else if (e.keyCode == 37 || e.keyCode == 39)
            return;
        else
            return quickSearch(this);
    });
    $('#quick-search').prev().bind('keydown', function(e) {
        if (e.keyCode == 13) {
            if (qscursor != -1) {
                window.location = $('#quick-search').find('a:first').attr('href');
                return false;
            }
            else {
                return true;
            }
        }
    });
    $('#quick-search').prev().bind('click', function(e) {
        if ($(this).next().is(':hidden'))
            return quickSearch(this, e);
        else
            return false;
    });
});
var ajaxqs = null;
var qscursor = -1;

function quickSearch(input) {
    var txtBox = $(input);
    if (!ajaxqs) {
        ajaxqs = $('#quick-search')
                 .css('top', (txtBox.outerHeight() + txtBox.offset().top + 7));
        ajaxqs.css('left', txtBox.position().left - ajaxqs.outerWidth() + txtBox.outerWidth());
    }

    if (txtBox.val().length > 2) {
        $.getJSON('/templates/pages/quicksearch.ashx', { q: txtBox.val() }, function(json) {
            ajaxqs.empty();
            if ((json.l.length > 0)) {
                $.each(json.l, function(i, item) {
                    var n = $('<div' + (i == 0 ? ' class="first"' : '') + '><a href="' + item.p + '">' + item.t + '</a></div>');
                    n.hover(function() {
                        var items = $('div', ajaxqs);
                        items.removeClass('active');
                        qscursor = items.index($(this));

                    }, function() {
                        qscursor = -1;
                    });
                    ajaxqs.append(n);
                });
                ajaxqs.show().append('<div id="qs-nfo">Tryck Enter f&#246r att <span>s&#246ka</span></div>');
            }
            else
                ajaxqs.hide();
        });
        qscursor = -1;
    }
    else
        ajaxqs.hide();

    return false;
}