﻿var browser = {
    isIE: navigator.appName == "Microsoft Internet Explorer" ? true : false,
    isOpera: navigator.appName == "Opera" ? true : false,
    isFF: !document.all && document.getElementById && !this.isOpera
}

var divOverText = "Loading...";

function $getEl(documentID) {

    if (document.all)//ie4
    {
        return document.all[documentID];
    }
    else if (document.getElementById) {//isIE6
        return document.getElementById(documentID);
    }
    else if (document.layers) {//isNS4
        return document.layers[documentID];
    }
    else if (document.getElementById && !document.all) {//isNS6
        return document.getElementById(documentID);
    }
}


function doNotAllowSelectionInDrp(index, sender) {
    if (sender.options.length <= 1)
        return;

    if (!sender.options[index].selected)
        return;

    if (index - 1 >= 0 && index - 1 < sender.options.length)
        sender.options[index - 1].selected = true;
    else if (index + 1 < sender.options.length)
        sender.options[index + 1].selected = true;
}

function addEvent(element, eventName, callback) {
    if (typeof (element) == "string")
        element = $getEl(element);
    if (element == null)
        return;
    if (element.addEventListener)
        element.addEventListener(eventName, callback, false);
    else if (element.attachEvent)
        element.attachEvent("on" + eventName, callback);
}

function removeEvent(element, eventName, callback) {
    if (typeof (element) == "string")
        element = $getEl(element);
    if (element == null)
        return;
    if (element.removeEventListener)
        element.removeEventListener(eventName, callback, false);
    else if (element.detachEvent)
        element.detachEvent("on" + eventName, callback);
}

function openPopup(url, target) {
    var _target = "WFSSPopup";
    if (null != target)
        _target = target;

    var settings = new popupSettings().getSettings(_target);
    window.open(url, _target,
                'status=' + settings.status +
                ',toolbar=' + settings.toolbar +
                ',menubar=' + settings.menubar +
                ',location=' + settings.location +
                ',scrollbars=' + settings.scrollbars +
                ',resizable=' + settings.resizable +
                ',height=' + settings.height +
                ',width=' + settings.width +
                ',left=' + settings.left +
                ',top=' + settings.top);
}

function popupSettings() {
    this.width = 1020;
    this.height = 756;
    this.location = 0;
    this.scroolbars = 0;
    this.resizable = 1;
    this.menubar = 0;
    this.toolbar = 0;
    this.status = 0;
    this.left = 0;
    this.top = 0;

    this.getAutoResponseSettings = function () {
        this.width = 700;
        this.height = 600;

        return this;
    }

    this.getTips = function () {
        this.width = 700; //620;
        this.height = 600; //300;

        return this;
    }

    this.getVote = function () {
        this.width = 700; //620;
        this.height = 370; //300;
        this.left = 200;
        this.top = 200;

        return this;
    }

    this.getChat = function () {
        this.width = 420;
        this.height = 505;
        this.left = 30;
        this.top = 30;
        this.toolbar = "no";
        this.location = "no";
        this.menubar = "no";
        this.resizable = "yes";
        return this;
    }


    this.getEmailChat = function () {
        this.width = 420;
        this.height = 550;
        this.left = 30;
        this.top = 30;
        this.toolbar = "no";
        this.location = "no";
        this.menubar = "no";
        return this;
    }

    this.getSettings = function (target) {
        switch (target.toLowerCase()) {
            case "autoresponse":
                return this.getAutoResponseSettings();
            case "tips":
                return this.getTips();
            case "vote":
                return this.getVote();
            case "chat":
                return this.getChat();
            case "emailchat":
                return this.getEmailChat();
            default:
                return this;
        }
    }
}

var wndHTML = null;
var tempSender = null;
var _wTitle = '';
function openPopupWithHTML(page, sender, target, wTitle, evt, sourceTagName) {
    evt = (null == event) ? evt : event;
    if ('a' == evt.srcElement.tagName.toLowerCase())
        return;
    var _target = "WFSSPopupHTML";
    if (null != target)
        _target = target;
    if (null != wTitle)
        _wTitle = wTitle;

    var _page = "about:blank";
    if (null != page)
        _page = page;
    if (null == wndHTML || wndHTML.closed)
        wndHTML = window.open(_page, _target, 'status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,height=756,width=1020,left=0,top=0');
    tempSender = sender;
    //debugger;
    setTimeout('wndHTML.document.body.innerHTML = tempSender.innerHTML;wndHTML.document.title=_wTitle;wndHTML.focus()');
}

//---------------------------------   Grid Style related -----------------------------------

var oldColor = '';
var oldSender = null;
function onGridRowMouseOver(sender, addPostBackRef, onClickCallBacks) {     //  debugger
    if (null == addPostBackRef)
        addPostBackRef = true;
    oldColor = sender.style.backgroundColor;
    sender.style.backgroundColor = '#FFFFDD';
    sender.style.cursor = 'pointer';
    sender.onclick = function () {   //debugger
        if (!addPostBackRef) {
            if (null != oldSender)
                oldSender.style.backgroundColor = '#FFFFFF';
            oldColor = sender.style.backgroundColor = '#FFEEFF';
            oldSender = sender;
            setTimeout(onClickCallBacks, 0);
            return;
        }
        var aList = sender.getElementsByTagName('a');
        for (var i = 0; i < aList.length; i++) {
            if (aList[i].href.indexOf('Select$') != -1) {
                if (aList[i].target)
                    window.open(aList[i].href, aList[i].target);
                else
                    window.location.href = aList[i].href;
                break;
            }
        }
    };
}

function onGridRowMouseOut(sender) {
    sender.style.backgroundColor = oldColor; //'#FFFFFF';
}

var repeaterItemOldColor = '';
function onRepeaterItemMouseOver(sender) {
    repeaterItemOldColor = sender.style.backgroundColor;
    sender.style.backgroundColor = '#FFFFDD';
    sender.style.cursor = 'pointer';
    sender.onclick = function () {

        var aList = sender.getElementsByTagName('a');
        for (var i = 0; i < aList.length; i++) {
            if (aList[i].id.indexOf('Select') != -1) {
                if (aList[i].target)
                    window.open(aList[i].href, aList[i].target);
                else
                    window.location.href = aList[i].href;
                break;
            }
        }
    };
}

function onRepeaterItemMouseOut(sender) {
    sender.style.backgroundColor = repeaterItemOldColor; //'#FFFFFF';
}

//---------------------------------  End Grid Style related -----------------------------------

function submitOnEnter(evt, linkButtonClientID, type) {//debugger;
    evt = (null != evt) ? evt : event;
    var keycode = '';
    if (evt.which)
        keycode = evt.which;
    else
        keycode = evt.keyCode
    if (keycode == 13) {
        if (null != type && type == "button")
            __doPostBack(linkButtonClientID, "");
        else
            window.location.href = $getEl(linkButtonClientID).href;
    }
}

function messagesCheckSpell(ftb) {
    if (ftb.GetHtml() != '')
        ftb.NetSpell();
}

//function AddBeginRequest(fn) {
//    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(fn);
//}

//function AddEndRequest(fn) {
//    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(fn);
//}

//function RemoveEndRequest(fn) {
//    Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(fn);
//}

function ValidateEmail(sender, asOneInstance, stringAlert) {
    if (sender.value == '')
        return true;
    var regEx = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
    if (asOneInstance) {
        if (!regEx.test(sender.value)) {
            alert(stringAlert);
            return false;
        }
    }
    else {
        var val = sender.value.replace(/ /g, '');
        var tokens = val.split(',');
        for (var i = 0; i < tokens.length; i++) {
            if (!regEx.test(tokens[i])) {
                alert(stringAlert);
                return false;
            }
        }
    }
    return true;
}

function GetBrowser() {
    if (navigator.appName == "Microsoft Internet Explorer")
        return "IE";
    return "NIE";
}

//*********************************************** treeview with checkboxes - check/uncheck feature for parent/childrens *******************************************

function initTree(treeViewClientID) {
    var treeElement = $getEl(treeViewClientID);
    var inputList = treeElement.getElementsByTagName("input");
    for (var i = 0; i < inputList.length; i++) {
        if (inputList[i].type.toLowerCase() != "checkbox")
            continue;

        inputList[i].onclick = function () {
            var childNodesContainer = $getEl(this.id.replace("CheckBox", "Nodes"));
            if (childNodesContainer == null)
                return;
            var childCheckBoxList = childNodesContainer.getElementsByTagName("input");
            for (var j = 0; j < childCheckBoxList.length; j++) {
                if (childCheckBoxList[j].type.toLowerCase() != "checkbox")
                    continue;
                childCheckBoxList[j].checked = this.checked;
            }
        }
    }
}

//*********************************************** SESSION TIMEOUT ********************************************

var sessionTimeout = null; //= 20 * 60 * 1000 - 25 * 1000;//milliseconds
var sessionTimeoutTracker = sessionTimeout;
var counter = 30; //seconds
var sessionIntervalID = null;
var trackSessionIntervalID = null;
var sessionTimeoutID = null;
var msg;

function StartSessionTracking() {
    sessionTimeoutTracker = sessionTimeout - (counter + 5) * 1000;
    try {
        clearInterval(trackSessionIntervalID);
    } catch (e) { }
    //window.status = "StartSessionTracking";
    updateSessionDiv();
    trackSessionIntervalID = setInterval("TrackSession()", 60 * 1000);
}
var divSessionId;
var divSessionIntervalId;
function updateSessionDiv() {
    try {
        var temp = sessionTimeoutTracker / 1000;
        $getEl(divSessionId).innerText = "ALOT: " + temp + "s";
    }
    catch (e) { }
}
function TrackSession() {
    if (sessionTimeoutTracker <= 60 * 1000)
        return;
    sessionTimeoutTracker -= 60 * 1000;
    updateSessionDiv();
    //window.status = sessionTimeoutTracker ;
    if (sessionTimeoutTracker <= 60 * 1000) {
        setTimeout("CloseSession()", (60 - counter - 5) * 1000);
        clearInterval(trackSessionIntervalID);
    }
}

function CloseSession() {
    counter = 30; //seconds
    msg = "Your session<br /> expires in " + counter + " secs";
    SessionDiv();
    sessionIntervalID = setInterval('remind()', 1000);
}

function ClearTimeout() {
    clearTimeout(sessionTimeoutID);
    sessionTimeoutID = null;
}

function remind() {
    counter--;

    msg = "Your session<br /> expires in " + counter + " secs";
    $getEl("sessionTextID").innerHTML = msg;
    if (counter == 0 && null != sessionIntervalID) {
        clearInterval(sessionIntervalID);
        sessionIntervalID = null;
        window.location = "../AutoLogOut.aspx";
    }
}

var sessionDiv = document.createElement('div');
var sessionIframe = document.createElement('iframe');
var sessionTxtSpan = document.createElement('span');
var sessionCancelBtn = document.createElement("input");

function setSizeOnSessionDiv() {
    var elHeight = (document.body.scrollHeight < document.body.clientHeight) ? document.body.clientHeight : document.body.scrollHeight;
    sessionDiv.style.width = document.body.clientWidth;
    sessionDiv.style.height = elHeight//clientHeight;

    sessionTxtSpan.style.top = parseInt(elHeight / 2) - 100;
    sessionTxtSpan.style.left = parseInt(document.body.clientWidth / 2) - 100;
    sessionTxtSpan.id = 'sessionTextID';

    sessionCancelBtn.style.top = parseInt(elHeight / 2);
    sessionCancelBtn.style.left = parseInt(document.body.clientWidth / 2) - 40;
    sessionCancelBtn.style.right = parseInt(document.body.clientWidth / 2) - 100;

    sessionIframe.style.width = document.body.clientWidth;
    sessionIframe.style.height = elHeight; //clientHeight;					
}

function SessionDiv(sessionDivDisplay) {
    if (null == sessionDivDisplay)
        sessionDivDisplay = 'block';
    sessionDiv.style.left = 0; //window.screenLeft;
    sessionDiv.style.top = 0; //window.screenTop;
    sessionDiv.style.display = sessionDivDisplay;
    sessionDiv.style.zIndex = 99999;
    sessionDiv.id = 'sessionDiv';
    sessionDiv.style.position = 'absolute';
    sessionDiv.style.filter = 'alpha(opacity=40)';
    sessionTxtSpan.innerHTML = msg;
    //sessionTxtSpan.style.position = 'relative';                                                

    sessionTxtSpan.style.position = 'absolute';
    sessionDiv.appendChild(sessionTxtSpan);
    sessionDiv.className = 'DivOver';
    sessionDiv.onmouseover = 'this.style.cursor = "wait"';
    //document.body.appendChild(sessionDiv);        

    sessionIframe.style.left = 0; //window.screenLeft;
    sessionIframe.style.top = 0; //window.screenTop;
    sessionIframe.style.display = sessionDivDisplay;
    sessionIframe.id = 'sessionIframe';
    sessionIframe.style.zIndex = 99999;
    sessionIframe.style.position = 'absolute';
    sessionIframe.style.filter = 'alpha(opacity=0)';
    sessionIframe.style.color = 'navy';
    sessionIframe.style.backgroundColor = 'white';
    sessionIframe.frameBorder = 0;
    sessionIframe.scrolling = 'no';
    sessionIframe.src = 'about:blank';
    sessionIframe.style.cursor = 'wait';
    sessionIframe.onmouseover = 'this.style.cursor = "wait"';
    document.body.appendChild(sessionIframe);

    document.body.appendChild(sessionDiv);

    sessionCancelBtn.type = "button";
    sessionCancelBtn.id = "btnCancel";
    sessionCancelBtn.value = "Cancel";
    sessionCancelBtn.style.fontWeight = "bold";
    sessionCancelBtn.style.backgroundColor = "white";
    sessionCancelBtn.style.position = "absolute";
    sessionCancelBtn.onclick = function () { history.go(0) };
    sessionDiv.appendChild(sessionCancelBtn);

    setSizeOnSessionDiv();
    window.onresize = setSizeOnSessionDiv;
}


function setHdnValue(value, hdnClientID) {
    $getEl(hdnClientID).value = value;
}

function setCheckValuesValue(val, hdnClientID, sender) {
    if (sender.checked) {
        $getEl(hdnClientID).value = $(hdnClientID).value + val + '#$423#';
    }
    else {
        $getEl(hdnClientID).value = $(hdnClientID).value.replace(val + '#$423#', "");
    }
}
window.onload = function () {
    try {
        var text = document.getElementById("ctl00_mainContentPlaceHolder_ctrlCreateTicket_txtDomainName").value;
    } catch (e) {
        var text = "";

    }
    try {
        var theInput = document.getElementById("ctl00_mainContentPlaceHolder_ctrlCreateTicket_txtDomainName");
        theInput.onblur = function () {
            var sender = this;

            if (sender.value == '') {
                sender.value = text;

                sender.style.color = '#888888';
            }
        }
        theInput.onfocus = function () {
            var sender = this;
            if (sender.value == text) {
                sender.value = '';
                sender.style.color = '#000000';
            }
        }
    } catch (e) { }
}
function toogleDefaultText(sender, text, evt) {
    evt = (null == evt) ? event : evt;

    if (evt.type == "focus") {
        if (sender.value == text) {
            sender.value = '';
            sender.style.color = '#000000';
        }
    }
    else if (evt.type == "blur") {
        if (sender.value == '') {
            sender.value = text;
            alert(text + " BLUR ");
            sender.style.color = '#888888';
        }
    }
}

function multiEditClick(sender, gridId, hdnStateId) {//debugger;
    sender.disabled = true;
    var oldMEditEnabled = !sender.checked; //($getEl(hdnStateId).value == "true") ? true : false;        
    if (!oldMEditEnabled)
        sender.value = "Normal Edit Mode";
    else
        sender.value = "Multi Edit Mode";

    sender.disabled = false;
    $getEl(hdnStateId).value = (!oldMEditEnabled).toString();
    setMultiEditContext(gridId, !oldMEditEnabled);
    return true;
}

function setMultiEditContext(gridId, mEditEnabled) {
    var grid = $getEl(gridId);
    var spanList = grid.getElementsByTagName('span');
    for (var i = 0; i < spanList.length; i++) {
        if (spanList[i].id.indexOf('lblCounter') != -1)
            spanList[i].style.display = mEditEnabled ? "none" : "block";
        if (spanList[i].id.indexOf('spanCkMEdit') != -1) {
            spanList[i].style.display = mEditEnabled ? "block" : "none";
            if (!mEditEnabled) {
                var ckList = spanList[i].getElementsByTagName("input");
                ckList[0].checked = false;
            }
        }
    }
}

var dbClickTarget = null;
var dbClickCount = 0;
function isDbClick(sender) {
    window.status = dbClickCount;
    if (dbClickTarget != sender) {
        dbClickTarget = sender;
        dbClickCount = 1;
        setTimeout("dbClickCount=0;", 1000);
        return false;
    }
    if (dbClickCount == 1) {
        dbClickCount = 0;
        return true;
    }
    else {
        setTimeout("dbClickCount=0;", 1000);
        dbClickCount++;
    }
    return false;
}



function escapeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

function openCodeWindow(sender, lnkId, txtAttachedId, url, modalId) {
    var txtId = sender.id.replace(lnkId, txtAttachedId);
    var txt = $getEl(txtId);
    var cPos = getCaretPos(txt); //(null == txt.selectionStart) ? 0 : txt.selectionStart;
    url = url + "?senderId=" + txtId + "&cPos=" + cPos;
    ModalFormShow(modalId, url);
    return false;
}

function setCode(textBoxId, cPos, encodedText) {
    var str = $getEl(textBoxId).value.substring(0, cPos);
    var str1 = $getEl(textBoxId).value.substring(cPos);
    str += encodedText + str1;
    $getEl(textBoxId).value = str;
}

function ModalFormSelfClose(timeoutScript) {
    var frameList;
    if (browser.isIE)
        frameList = window.parent.document.frames;
    else
        frameList = window.parent.frames;
    var fId;
    for (var i = 0; i < frameList.length; i++) {
        fId = frameList[i].frameElement.id;
        if (fId.indexOf('_iframe') != -1)
            window.parent.ModalFormHide(fId);
    }
    if (timeoutScript)
        setTimeout("window.parent." + timeoutScript, 0);
    //window.parent.ModalFormHide(fId);
}



function getCaretPos(textarea) {
    var caretPos = 0;
    textarea.focus();
    // get selection in firefox, opera, …    
    if (typeof (textarea.selectionStart) == 'number') {
        caretPos = textarea.selectionStart
    }
    else if (document.selection) {
        var selection_range = document.selection.createRange().duplicate();

        if (selection_range.parentElement() == textarea) { // Check that the selection is actually in our textarea
            // Create three ranges, one containing all the text before the selection,
            // one containing all the text in the selection (this already exists), and one containing all
            // the text after the selection.
            var before_range = document.body.createTextRange();
            before_range.moveToElementText(textarea); // Selects all the text
            before_range.setEndPoint("EndToStart", selection_range); // Moves the end where we need it

            var after_range = document.body.createTextRange();
            after_range.moveToElementText(textarea); // Selects all the text
            after_range.setEndPoint("StartToEnd", selection_range); // Moves the start where we need it

            var before_finished = false, selection_finished = false, after_finished = false;
            var before_text, untrimmed_before_text, selection_text, untrimmed_selection_text, after_text, untrimmed_after_text;

            // Load the text values we need to compare
            before_text = untrimmed_before_text = before_range.text;
            selection_text = untrimmed_selection_text = selection_range.text;
            after_text = untrimmed_after_text = after_range.text;

            // Check each range for trimmed newlines by shrinking the range by 1 character and seeing
            // if the text property has changed. If it has not changed then we know that IE has trimmed
            // a \r\n from the end.
            do {
                if (!before_finished) {
                    if (before_range.compareEndPoints("StartToEnd", before_range) == 0) {
                        before_finished = true;
                    } else {
                        before_range.moveEnd("character", -1)
                        if (before_range.text == before_text) {
                            untrimmed_before_text += "\r\n";
                        } else {
                            before_finished = true;
                        }
                    }
                }
                if (!selection_finished) {
                    if (selection_range.compareEndPoints("StartToEnd", selection_range) == 0) {
                        selection_finished = true;
                    } else {
                        selection_range.moveEnd("character", -1)
                        if (selection_range.text == selection_text) {
                            untrimmed_selection_text += "\r\n";
                        } else {
                            selection_finished = true;
                        }
                    }
                }
                if (!after_finished) {
                    if (after_range.compareEndPoints("StartToEnd", after_range) == 0) {
                        after_finished = true;
                    } else {
                        after_range.moveEnd("character", -1)
                        if (after_range.text == after_text) {
                            untrimmed_after_text += "\r\n";
                        } else {
                            after_finished = true;
                        }
                    }
                }

            } while ((!before_finished || !selection_finished || !after_finished));

            // Untrimmed success test to make sure our results match what is actually in the textarea
            // This can be removed once you’re confident it’s working correctly
            var untrimmed_text = untrimmed_before_text + untrimmed_selection_text + untrimmed_after_text;
            var untrimmed_successful = false;
            if (textarea.value == untrimmed_text) {
                untrimmed_successful = true;
            }
            // ** END Untrimmed success test

            caretPos = untrimmed_before_text.length;
        }
    }
    return caretPos;
}

function simulateEvent(elem, eventName) {
    if (typeof (elem) == "string") {
        elem = $get(elem);
    }

    if (document.createEvent) {
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent(eventName, true, false);
        elem.dispatchEvent(evObj);
    } else if (document.createEventObject) {
        elem.fireEvent('on' + eventName);
    }
}

var articlesLiveSearch = {
    txtSearch: null,
    container: null,
    resultsContainer: null,
    prevSearchTerm: '',
    nextPage: 1,
    defaultPageSize: 10,
    pageSize: null,
    pageCallbackFlag: false,
    maxPageNo: 1,
    allowEmptySearchTerm: true,
    getNextPageFromCookie: function () {
        var page = 1;
        try {

            if (null != $.cookie('LiveSearchNextPage'))
                page = parseInt($.cookie('LiveSearchNextPage'));
            else page = 0;
        } catch (e) { }
        return page;
    },
    saveNextPageToCookie: function (val) {
        if (val < 0)
            val = 0;
        if (val >= this.maxPageNo)
            val = this.maxPageNo - 1;

        $.cookie('LiveSearchNextPage', val);
    },
    init: function (txtSeachClientID, liveSearchContainerID, _allowEmptySearchTerm) {
        try {
            this.pageSize = this.defaultPageSize;
            this.txtSearch = $("#" + txtSeachClientID);
            this.container = $("#" + liveSearchContainerID);
            this.allowEmptySearchTerm = null == _allowEmptySearchTerm ? true : _allowEmptySearchTerm;
            this.resultsContainer = $(this.container).find("div:first");
        } catch (e) { }
        if (null == this.txtSearch || null == this.resultsContainer || null == this.container) {
            alert("Articles live Search failed to initialize");
            return;
        }
        if (true == this.allowEmptySearchTerm || $(this.txtSearch).val()) {//rebuild the state - applies when client uses the back button of website                                
            this.nextPage = this.getNextPageFromCookie(); //0;
            $(this.resultsContainer).html("");
            this._search();
            this.prevSearchTerm = $(this.txtSearch).val();
        }
        $(this.txtSearch).bind('keyup', { sender: this }, function (event) {
            if (event.data.sender.prevSearchTerm == $(event.data.sender.txtSearch).val())//nothing changed
                return;

            event.data.sender.pageCallbackFlag = false;
            event.data.sender.prevSearchTerm = $(event.data.sender.txtSearch).val();
            event.data.sender.nextPage = 0;
            event.data.sender.saveNextPageToCookie(null);
            $(event.data.sender.resultsContainer).html("");
            event.data.sender._search();
        });
    },
    moveToNextPage: function () {
        this.nextPage++;
        //alert(this.nextPage);
        this.changePage();
    },
    moveToPrevPage: function () {
        this.nextPage--;
        this.changePage();
    },
    changePage: function (sender) {
        this.saveNextPageToCookie(this.nextPage);
        this.nextPage = this.getNextPageFromCookie(); // validate the oage number
        this.pageCallbackFlag = true;
        this._search();
    },
    _resultsReceived: function (data) {
        articlesLiveSearch.pageSize = articlesLiveSearch.defaultPageSize;
        $(articlesLiveSearch.resultsContainer).parent().show();
        data = data.replace("onchange", "onchange_disabled");
        var searchRes = $(data).find('table[id$="dlArticles"]').wrap("<div></div>").parent().html();
        var msg = $(data).find('span[id$="lblNoMatchFound"]').wrap("<div></div>").parent().html();
        var resCount = $(data).find('h3[id$="lblArticleFound"]').wrap("<div></div>").parent().html();

        var html = msg + resCount + searchRes;

        if (articlesLiveSearch.nextPage > 0) {
            html = $(articlesLiveSearch.resultsContainer).html() + searchRes;
        }

        html = $(data).find(".searchResults").css("display", "block").wrap("<div></div>").parent().html();
        $(articlesLiveSearch.resultsContainer).html(html);


        var lnkPrev = $(articlesLiveSearch.resultsContainer).find("a[id$='lnkPrev']");
        var lnkNext = $(articlesLiveSearch.resultsContainer).find("a[id$='lnkNext']");
        var ddlPageIndex = $(articlesLiveSearch.resultsContainer).find("select[id$='ddlPageIndex']");

        $(articlesLiveSearch.resultsContainer).find("a").each(function (index, item) {
            $(item).attr("href", $('a[id$="hlnkAnswers"]').attr("href") + $(item).attr("href"));
        });

        articlesLiveSearch.maxPageNo = parseInt($(ddlPageIndex).find("option:last").val());

        $(lnkPrev).attr("href", "javascript:articlesLiveSearch.moveToPrevPage();")
        $(lnkNext).attr("href", "javascript:articlesLiveSearch.moveToNextPage();")
        $(ddlPageIndex).change(function (event) {
            articlesLiveSearch.nextPage = parseInt(this.options[this.selectedIndex].value) - 1;
            articlesLiveSearch.changePage();
        });

        //articlesLiveSearch.nextPage = parseInt(ddlPageIndex.options[ddlPageIndex.selectedIndex].value) - 1;
        //alert(articlesLiveSearch.nextPage);
        //$(articlesLiveSearch.resultsContainer).stop(true, true).fadeIn('slow');
        //articlesLiveSearch.saveNextPageToCookie(articlesLiveSearch.nextPage);
    },
    _search: function () {
        if (!this.allowEmptySearchTerm && $(this.txtSearch).val().replace(/ /g, "") == "") {
            $(this.resultsContainer).parent().hide();
            return;
        }
        $.ajax({
            type: "GET",
            cache: false,
            async: true,
            url: '../answers.aspx?searchTerm=' + encodeURI($(this.txtSearch).val()) + '&page=' + this.nextPage + '&pageSize=' + this.pageSize,
            success: this._resultsReceived
        });
    }

}

function initPlayer() {
    var overlay = $(".overlay").overlay({

        // use the Apple effect for overlay
        effect: 'apple',

        // 1. start expose effect when overlaying begins
        mask: '#123448',

        fixed: false,

        // 2. when overlay is loaded, we reposition and resize the player on top of it
        onLoad: function () {

            // get handle to the embed element
            var embed = $("#player :first");

            /* and reposition / resize it. you will propably have to tweak
            these when placing this on your site */

            var el = this.getOverlay();
            var height = el.height();
            embed.css({
                // size
                width: parseInt(el.width()) - 80,
                height: parseInt(el.height()) - 80,
                // position
                left: parseInt(el.css("left")) + 40,
                top: parseInt(el.css("top")) + 40
            });
            

            // while overlay was growing we were in the paused state

            $f().resume();
        },

        // when overlay closes
        onClose: function () {

            // 1. return our player to its original size/position
            $("#player :first").css({ top: null, left: null, width: null, height: null });

            // 2. enable the fullscreen button again
            $f().getControls().enable({ fullscreen: true });
        }

    }).data("overlay");



// install flowplayer on the container
$f("player", "http://www.123-reg.co.uk/support/videos/flowplayer.commercial-3.2.7-3.swf", {

    onLoad: function () {
        var logo = this.getPlugin("logo");
        logo.css({ "left": 30, "bottom": 20 });
        this.css('position', 'fixed');
    },
    // our fake fullscreen action.
    onBeforeFullscreen: function () {

        // 1. launch overlay
        overlay.load();

        // 2. pause the player and make it hidden while overlay "grows"
        this.hide().pause();

        // 3. disable fullscreen button when overlayed          
        this.getControls().enable({ fullscreen: false });
       

        // $("player_api").css(position, 'fixed');
        $("img[src$='petrol.png']").remove();
        // 4. disable normal fullscreen action by returning false
        return false;
    },

    // when ESC is pressed above the player, "fullscreen" is closed
    onKeyPress: function (key) {
        if (key == 27) {
            overlay.close();
        }
    },


    // in this case, use the commercial version for a change
    key: '#@518151582d115a357bd',

    // some basic visual setups

    canvas: { backgroundGradient: 'none' },
    clip: { autoPlay: false, autoBuffering: true }

});

};

