﻿// JScript File
var empty = -77;
var _activeHyper
var m_intIndex = 1;
var dir = 1;
var imgNo = 1;
var slideShowSpeed = 3000
var crossFadeDuration = 3
var Pic = new Array();
var advertMother = new Array();
var advertNext = new Array();
var advertCurrent = new Array();
var advertMax = new Array();
var advertCount = -1;
var ajaxSuccessMsg = '';
var advertMax = -1;
var lastPopup = '';
var lastAdvertMother;
var lastFUCtrl = 0;
var lastFCTimeOut = 0;
var lastTree = '';
var isCombos = new Array();
var isComboCount = 0;
var mouseX = 0;
var mouseY = 0;
var maxZindex = 25;
var lastDivName, lastTxtName, lastObjTomove = 0, layId = 0, lastObjTomoveIsImage = false;
var fileMode = 'editor';
var rolTxtNo = 1;
var editorPass = false;
var posMode = 'move';
var editPosX, editPosY
var bbold;
var focusRange;
var lastNode;
var startUpScriptCount = 0;
var ajaxErrorMsg = '';
var vtot = 0;
var OncePlayed = false;
var lastvGuid = '';
var activeVideo = '';
var lastZPara = ''
var isMoving = false;

function videoInfo() {
    this.guid = '';
    this.vid = 0;
    this.songName = '';
    this.zaps = '';
    this.viewed = '';
    this.href = '';
    this.OncePlayed = 0;
}

function AddHeight(divName) {
    var div = document.getElementById(divName);
    var hgt = div.offsetHeight;
    div.style.height = hgt + 20;
}

function AddParam(paramName, paramVal, addComma) {
    var temp = '';
    if (paramVal == 'undefined')
        paramVal = '';

    temp = "\"" + paramName + "\":\"" + paramVal + "\""
    if (addComma)
        temp = temp + ',';
    return temp;
}

function CallAjaxOnServer(method, dataParamIn, functionToCallsuccess, paramCustom) {
    //dataParamIn = AddParam('key1','pval1') + ',' + AddParam('key2','pval2')
    var path = GetPath(method);
    var dataParam = '{' + dataParamIn + '}';
    ajaxErrorMsg = '';
    $.ajax({
        type: "POST",
        url: path,
        contentType: "application/json; charset=utf-8",
        data: dataParam,
        dataType: "json",
        success: function (msg) {
            ajaxSuccessMsg = msg;
            if (functionToCallsuccess != '')
                eval(functionToCallsuccess + '("' + msg + '","' + paramCustom + '");');
        },
        error: function (xhReq) {
            var serverResponse = xhReq.responseText;
            ajaxErrorMsg = 'There was an error sending data to server.' + serverResponse + '] : ' + dataParam;
            if (useAlerts)
                alert(ajaxErrorMsg);
        }
    });

}

function InsertImageInEditor(img, edt) {
    var result = window.showModalDialog('ftb.imagegallery.aspx?rif=~/' + img + '/&cif=~/' + img + '/&ftb=' + edt);
}

function ISComboOnShowDropDown(controlId, left, top, width, height) {
    var cboCombo = ISGetObject(controlId);
    cboCombo.DoResize();
    return true;
}

function showWait() {

    $('#progDiv').css({ display: 'block' });

}

function addCombo(comboName) {
    isCombos[isComboCount] = comboName;
    isComboCount++;
}

//controlId, left, top, width, height
function fixCombos() {
    for (var i = 0; i < isComboCount; i++) {

        var cboCombo = ISGetObject(isCombos[i]);
        cboCombo.DoResize();
        // cboCombo.GetFrameElement().parentElement.style.styleFloat = "";
    }
}

//controlId, left, top, width, height
function InitISCombo(controlId) {
    var cboCombo = ISGetObject(controlId);
    cboCombo.DoResize();
    return true;
}

function chkfix(chkName) {
    var hchk = document.getElementById(chkName);
    if (hchk.value == '1')
        hchk.value = '0';
    else
        hchk.value = '1';

}


function FUPopup(FUCtrl, positionCtrlName, title, global, width, height, left) {
  
    var positionCtrl = null;
    if (positionCtrlName != '')
        positionCtrl = $('#' + positionCtrlName)

    if (!width)
        width = 500;

    if (!height)
        height = 300;
    // alert(positionCtrl);

    if ($('#' + FUCtrl)) {
        var pos;

        if ($('#' + FUCtrl).css('display') == 'none') {
            if (positionCtrl != null) {
                pos = $(positionCtrl).offset();
                pos.left -= $('#divInsideFrame').position().left;
                pos.top += 20;

                $('#' + FUCtrl).dialog({ 'height': height, 'width': width, title: title, position: pos, close: function (event, ui) { closeFUPopup(); } });
            }
            else {

                if (left != null) {

                    pos = $('#roll').offset();
                    pos.left = left;
                    pos.top = 0;
                    $('#' + FUCtrl).dialog({ 'height': height, 'width': width, title: title, position: pos, close: function (event, ui) { closeFUPopup(); } });
                }
                else {
                    $('#' + FUCtrl).dialog({ 'height': height, 'width': width, title: title, close: function (event, ui) { closeFUPopup(); } });
                }
            }

            if (global == undefined || global == false)
                $('#' + FUCtrl).parent().appendTo($('#divInsideFrame'));
            else
                $('#' + FUCtrl).parent().appendTo($('.mainForm'));

        }
        else {

            if (positionCtrl != null) {
                pos = $(positionCtrl).offset();
                pos.top += 20;
            }

            $('#' + FUCtrl).dialog('open');
            if (positionCtrl != null)
                $('#' + FUCtrl).dialog('option', 'position', pos);
        }
        // $('#'+FUCtrl).dialog('position',pos);
    }
    lastFUCtrl = FUCtrl;
    return false;
}

function GetZIndex() {
    maxZindex++;
    return maxZindex;
}
function GetZIndexBig() {
    maxZindex = maxZindex + 100;
    return maxZindex;
}

function tree(divName, parentName) {
    if (lastTree != '')
        if (document.getElementById(lastTree))
            document.getElementById(lastTree).style.display = 'none';

    if (document.getElementById(parentName)) {
        if (document.getElementById(divName).style.display == '') {
            document.getElementById(divName).style.display = 'none';
        }
        else {
            var parentObj = document.getElementById(parentName);
            var x = findPosX(parentObj);
            var y = findPosY(parentObj);
            document.getElementById(divName).style.position = 'absolute';
            document.getElementById(divName).style.left = x - 50;
            document.getElementById(divName).style.top = y + 25;
            document.getElementById(divName).style.display = '';
            document.getElementById(divName).style.zIndex = GetZIndex();
            lastTree = divName;
        }
    }
    return false;
}

function FUClose() {
    if (document.getElementById(lastFUCtrl))
        document.getElementById(lastFUCtrl).style.display = 'none';
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent)
        while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent)
        while (1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}


function show_popup1() {
    show_popup(intIndex);
}

function show_popup2(intIndex) {
    show_popup(intIndex, false);
}

function ShowSelPanel(pnlName) {
    var pnl = document.getElementById(pnlName);
    if (pnl.style.display == '')
        pnl.style.display = 'none';
    else
        pnl.style.display = '';

    pnl.style.zIndex = GetZIndex();

    return false;
}

function show_popup(intIndex, blnDontBrowse, intDirId) {
    var objWin, intHgt, intWidth, intLeft, intDiff, intTop, strScroll, strFile

    m_intIndex = intIndex;

    strScroll = 'no'

    dir = intDirId;


    if (blnDontBrowse) {
        intHgt = 200
        intTop = (window.screen.availHeight / 2) - (intHgt / 2)
        intWidth = (window.screen.availWidth / 2)
        intLeft = intWidth - (intWidth / 2)

        strFile = "upload.aspx?index=" + intIndex + "&dir=" + dir;
    }
    else {
        intHgt = 670
        intTop = ((window.screen.availHeight / 2) - (intHgt / 2)) - 40;
        intWidth = (window.screen.availWidth / 2) + 20
        intLeft = intWidth - (intWidth - 50)

        strFile = "FileBrowse.aspx?index=" + intIndex + "&dir=" + dir;
    }

    strSettings = "top=" + intTop + " left=" + intLeft + " width=" + intWidth + " height=" + intHgt + " resizable=yes scrollbars=" + strScroll + " menubar=no titlebar=no toolbar=no location=no "

    objWin = window.open(strFile, "frmLookupWindow", strSettings)
}

function showNextImage(aname) {
    imgNo++;
    if (imgNo > 14)
        imgNo = 1;

    var obj = document.getElementById(aname);
    if (obj) {
        obj.style.filter = "blendTrans(duration=2)";
        obj.style.filter = "blendTrans(duration=crossFadeDuration)";
        obj.filters.blendTrans.Apply();
        obj.src = 'rotate/img' + imgNo + '.jpg';
        obj.filters.blendTrans.Play()

        var f = "showNextImage('" + aname + "');";
        window.setTimeout(f, 4000);

        var preLoad = new Image(100, 25);
        var nextImg = imgNo + 1;
        if (nextImg > 43)
            nextImg = 1;

        preLoad.src = 'rotate/img' + nextImg + '.jpg';

    }

}

function preLoad(src) {
    var pic1 = new Image(50, 50);
    pic1.src = src;
}


function refreshAdvert(advertCtrlBtnName) {
    setTimeout("document.getElementById('" + advertCtrlBtnName + "').click();refreshAdvert('" + advertCtrlBtnName + "');", 20000);
}


function uploadFile(hyperLink) {
    var objWin, intHgt, intWidth, intLeft, intDiff, intTop, strScroll, strFile
    var captionFld, guidFld, intDirId

    _activeHyper = document.getElementById(hyperLink);

    //.getAttribute

    captionFld = _activeHyper.getAttribute('captionFld');
    guidFld = _activeHyper.getAttribute('guidFld');
    intDirId = _activeHyper.getAttribute('folder');
    var iWidth = _activeHyper.getAttribute('iWidth');
    var iHeight = _activeHyper.getAttribute('iHeight');

    strScroll = 'no'

    dir = intDirId;

    intHgt = 200
    intTop = (window.screen.availHeight / 2) - (intHgt / 2)
    intWidth = (window.screen.availWidth / 2)
    intLeft = intWidth - (intWidth / 2)

    strFile = "upload.aspx?index=777&c=" + captionFld + "&g=" + guidFld + "&dir=" + dir + "&i=" + hyperLink + "&w=" + iWidth + "&h=" + iHeight;
    //strFile = "upload.aspx?i=" + hyperLink;

    strSettings = "top=" + intTop + " left=" + intLeft + " width=" + intWidth + " height=" + intHgt + " resizable=yes scrollbars=" + strScroll + " menubar=no titlebar=no toolbar=no location=no "

    objWin = window.open(strFile, "frmLookupWindow", strSettings)
}

function regAdvert(column, mother, nextImage, maxImageCount) {
    advertMax++;
    advertMother[advertMax] = mother;
    advertNext[advertMax] = nextImage;
    advertCurrent[advertMax] = 0;
    advertMax[advertMax] = maxImageCount;

    if (lastAdvertMother != mother)
        window.setTimeout("nextAdvert('" + mother + "'," + advertMax + ")", 3000);

    lastAdvertMother == mother;
}

function nextAdvert(motherCtrl, index) {
    advertCurrent[index] += 1;

    if (advertCurrent[index] > -1) {
        if (advertCurrent[index] > advertMax[index])
            advertCurrent[index] = 0;

        var adCount = 0;
        var adFound = false;
        for (i = 0; i <= advertMax; i++) {
            if (advertMother[i] == motherCtrl) {
                adCount++;
                if (adCount >= advertCurrent[index]) {
                    adFound = true;
                    showAdvert(motherCtrl, advertNext[i]);
                    break;
                }
            }

        }
        if (!adFound)
            advertCurrent[index] = -1;
    }

    window.setTimeout("nextAdvert('" + motherCtrl + "'," + index + ")", 3000);
}

function showAdvert(mother, next) {
    motherObj = document.getElementById(mother)
    nextObj = document.getElementById(next);
    if (motherObj.urlCtrl) {
        var urlCtrl = document.getElementById(motherObj.urlCtrl);
        urlCtrl.value = nextObj.title;
    }

    if (motherObj != null) {
        motherObj.src = nextObj.src;
        motherObj.title = nextObj.title;

    }
    //alert(nextObj.src)
}



function moveOverPopup() {
    if (lastPopup != 0)
        clearTimeout(lastPopupHandle);

    lastPopupHandle = window.setTimeout('closeLastPopup();', 5000);
}

function closeLastPopup() {
    if (lastPopup != '') {
        $('#' + lastPopup).removeClass('browsePopupShow').addClass('browsePopupHide');
    }

}

function placeImage(caption, guid) {

    var guidFld = document.getElementById(_activeHyper.getAttribute('guidFld'));
    var captionFld = document.getElementById(_activeHyper.getAttribute('captionFld'));
    var lnkCtrl;
    if (_activeHyper.lnkCtrl != '')
        lnkCtrl = document.getElementById(_activeHyper.getAttribute('lnkCtrl'));
    var activeImage = _activeHyper.getAttribute('imgCtrl');

    var folder = _activeHyper.getAttribute('folderPath');

    captionFld.value = caption;

    guidFld.value = guid;
    var imgCtrl = document.getElementById(activeImage);
    var path = folder + '/' + guidFld.value;
    //alert(path)

    if (_activeHyper.getAttribute('lnkCtrl') != '') {
        if (_activeHyper != null && _activeHyper.getAttribute('lnkCtrl') != null)
            _activeHyper.getAttribute('lnkCtrl').onClick = "openDoc('" + path + "');return false;";
    }
    else {
        imgCtrl.src = path;
    }

}

function openDoc(doc) {
    window.open(doc);
}


function lite2(obj) {
    if (document.all && !window.opera) {
        obj.filters.blendTrans.apply();
        obj.filters.blendTrans.play();
    }
}

function flashClickUpdate() {
    objects = document.getElementsByTagName("object");
    for (var i = 0; i < objects.length; i++) {
        objects[i].outerHTML = objects[i].outerHTML;
    }
}

function MiniMenu(lastScreen, tableName) {
    var lastMiniTable = document.getElementById(lastScreen).value;
    if (lastMiniTable != '')
        document.getElementById(lastMiniTable).style.display = 'none';

    document.getElementById(tableName).style.display = '';
    document.getElementById(lastScreen).value = tableName;

    return (false);

}

function confirm_delete() {
    if (confirm("Are you sure you want to delete the record?") == true)
        return true;
    else
        return false;
}



//window.setTimeout("flashClickUpdate();",10);

var onceOpen = 0;

function openDocOnce(url) {
    if (onceOpen == 0) {
        onceOpen = 1;
        window.open(url);
    }
}

function position(elmIdOrClass, x, y) {
    var pos = $('#TopLeft').position();
    pos.top += y;
    pos.left += x;
    $(elmIdOrClass).css({ 'position': 'absolute', 'top': pos.top + 'px', 'left': pos.left + 'px' });

}

function positionAndDisplay(elmIdOrClass, x, y) {
    var pos = $('#TopLeft').position();
    pos.top += y;
    pos.left += x;
    $(elmIdOrClass).css({ 'position': 'absolute', 'top': pos.top + 'px', 'left': pos.left + 'px', 'display': 'block' });

}

function AnimateMenuOnHover() {
    $('#jmenuBar a').hover(function () {
        //my:'left top',at:'left top'
        var pos = $(this).position();
        var pwidth = $(this).width() + 30; // + $(this).css('paddingLeft');
        var pheight = $(this).height();
        $('#marker').css({ display: 'inline', position: 'absolute' });
        // $('#marker').addClass('onTop');
        $('#marker').stop(true, true).animate({ top: pos.top, left: pos.left - 10, opacity: 1, width: pwidth, height: pheight }, 800, function () {
            // $(this).effect('shake',80);
        });
        //$(this).corner('cc:#009 8px').animate({top:'-=10',fontSize:'18pt',backgroundColor:'black',color:'white',width:'300'},1000);
        //$(this).flip({direction:'lr',onEnd:function(){
        //            $(this).revertFlip().animate({top:+8},500);
        //}});            

    }
                   , function () {

                       $('#marker').animate({ left: 0, width: 1000, top: -100, opacity: 0, height: 300 }, 300, function () {


                           $('#marker').css({ display: 'none', position: 'absolute' });
                           $('#jmenuBar a').css({ display: 'inline' });
                       });



                   });

}

function updateMove(ui, divToMove, btnUpdate, txtCtrlName) {

    $('#' + btnUpdate).parent().appendTo($("form:first"));
    // $('#' + txtCtrlName).val(ui.absolutePosition.top + ', ' + ui.absolutePosition.left);
    $('#' + btnUpdate).click();
}


function DragNow(ctrl) {
    var zindex = GetZIndex();
    ctrl.css({ 'z-Index': zindex }).draggable();
}

//run the currently selected effect
function runEffect() {

    $(".Drag").mousedown(function () { DragNow($(this)); });

    //get effect type from 
    var selectedEffect = 'bounce';
    //var selectedEffect = 'clip';

    //most effect types need no options passed by default
    var options = {};
    //check if it's scale, transfer, or size - they need options explicitly set
    //if(selectedEffect == 'scale'){ options = {percent: 0}; }
    //	else if(selectedEffect == 'transfer'){ options = { to: "#button", className: 'ui-effects-transfer' }; }
    //else if(selectedEffect == 'size'){ options = { to: {width: 200,height: 60} }; }

    //run the effect
    $(".BoxBounce").effect(selectedEffect, options, 500, function () {
        $(".BoxBounce").draggable().resizable();

    });

};

function moveScroll(scroll, slider, delta) {
    elmScroll = '#' + scroll;
    elmSlide = '#' + slider;
    var maxScroll = $(elmScroll).attr('scrollHeight') - $(elmScroll).height();
    var scrollTopVal = $(elmScroll).attr('scrollTop');
    var pos = scrollTopVal;

    if (delta > 0)
        pos -= 100;
    else
        pos += 100;

    if (pos > maxScroll)
        pos = maxScroll;

    var percent = 100 - parseInt(((pos / maxScroll) * 100));

    $(elmSlide).slider({ value: percent });
    $(elmScroll).attr('scrollTop', pos);
}

function myScrollBar(paraId, scroll, slider, height) {
    var elmScroll = '#' + scroll;
    var elmSlide = '#' + slider;
    var elmPara = '#' + paraId;



    $(elmScroll).bind('mousewheel', function (event, delta) { moveScroll(scroll, slider, delta); return false; });
    $(elmScroll).css('height', height + 'px');
    $(elmSlide).css('height', height - 20 + 'px');
    $(elmSlide).slider({ animate: true, change:
	        function (e, ui) {
	            //handleSliderChange
	            var maxScroll = $(elmScroll).attr('scrollHeight') - $(elmScroll).height();
	            $(elmScroll).animate({ scrollTop: ((100 - ui.value) * (maxScroll / 100)) }, 1000);
	        }

	    , slide:
	        function (e, ui) {
	            //handleSliderSlide
	            var maxScroll = $(elmScroll).attr('scrollHeight') - $(elmScroll).height();
	            $(elmScroll).attr({ scrollTop: ((100 - ui.value) * (maxScroll / 100)) });
	        }
	    , orientation: 'vertical', value: 100
    });

}



function mPosLeft(mTextCtrl, pos) {
    $('#' + mTextCtrl).css({ display: 'inline', position: 'relative' });
    $('#' + mTextCtrl).animate({ 'position': 'relative', 'left': pos + 'px' }, 300)

}

function mPosTop(mTextCtrl, pos) {

    $('#' + mTextCtrl).css({ display: 'inline', position: 'relative' });
    $('#' + mTextCtrl).animate({ 'position': 'relative', 'top': pos + 'px' }, 300)
}



function MU(scroll, slider) {

    var val = GetSliderVal(slider)
    val = val + 30;
    MoveSlider(slider, val);
    MoveCanvas(scroll, val);
    return false;
}

function MD(scroll, slider) {

    var val = GetSliderVal(slider)
    val = val - 30;
    MoveSlider(slider, val);
    MoveCanvas(scroll, val);
    return false;
}

function GetSliderVal(slider) {
    var elmSlide = '#' + slider;
    return $(elmSlide).slider("option", "value");
}

function MoveSlider(slider, val) {
    var elmSlide = '#' + slider;
    if (val > 100)
        val = 100;
    if (val < 0)
        val = 0;

    $(elmSlide).slider({ value: val });
}

function MoveCanvas(scroll, val) {
    var elmScroll = '#' + scroll;
    var maxScroll = $(elmScroll).attr('scrollHeight') - $(elmScroll).height();

    if (val > 100)
        val = 100;
    if (val < 0)
        val = 0;
    $(elmScroll).animate({ scrollTop: ((100 - val) * (maxScroll / 100)) }, 1000);

}

function ShowEditMnu(mnuName) {
    $('#' + mnuName).css({ 'display': 'block' });

    return false;
}

function RegPara(div, editButtons, txtInfo, usexy) {
    var origInfo = '';
    $('#' + div).resizable({
        stop: function (event, ui) {
            var id = $(this).attr('id').substring(1);
            ResizePara(id, ui.size.width, ui.size.height);
        }
    });
    $('#' + div).hover(
            function () {
                if (isMoving)
                    return;
                var zindex = GetZIndex();
                var newTop = $('#' + div).position().top + 'px';
                var newLeft = ($('#' + div).position().left + 90) + 'px';
                origInfo = $('#' + txtInfo).val();
                var info = origInfo + ' Coord:' + newTop + ' ' + newLeft;
                $('#' + txtInfo).val(info);
                $('#' + txtInfo).css({ 'display': 'inline' });
                $('#' + txtInfo).click(function () {
                    $('#' + txtInfo).css({ 'display': 'none' })
                });
                //    $('#' + editButtons).css({'display':'block','Z-Index':zindex,'left':'0px','top':'-8px'});
                $('#' + div).css({ 'opacity': '1', 'border-style': 'solid', 'border-width': '1px' });
            }
            ,
            function () {
                if (isMoving)
                    return;
                $('#' + txtInfo).val(origInfo);
                $('#' + editButtons).css({ 'display': 'none' });
                $('#' + div).css({ 'opacity': '0.4', 'border-style': 'none', 'border-width': '0px' });
            }
        );
}

function movePara(divToMove, moveIcon, txtCtrlName, btnUpdate, usexy) {
    var offsetTop = 0;
    var offsetLeft = 0;
    if (isMoving)
        return;

    isMoving = true;
    if (usexy == 'False') {
        offsetTop = (mouseY - $('#' + divToMove).position().top);//  - 16;
        offsetLeft = (mouseX - $('#' + divToMove).position().left); 
      //  Dino compare rootDiv to #viewport ********************************
        $('#' + divToMove).draggable({ handle: '#' + moveIcon, drag: function (event, ui) {
            var newTop = mouseY - offsetTop;
            var newLeft = mouseX - offsetLeft;
            $('#' + txtCtrlName).val(newTop + ', ' + newLeft);
        }, stop: function (event, ui) {
            updateMove(ui, divToMove, btnUpdate, txtCtrlName);
            isMoving = false;
        }
        });
    }
    else {
        offsetTop = (mouseY - $('#' + divToMove).position().top);//  - 16;
        offsetLeft = (mouseX - $('#' + divToMove).position().left);
        //alert(offsetTop);
        $('#' + divToMove).draggable({ handle: '#' + moveIcon, drag: function (event, ui) {
            var newTop = mouseY - offsetTop;
            var newLeft = mouseX - offsetLeft;
            $('#' + txtCtrlName).val(newTop + ', ' + newLeft);
        }, stop: function (event, ui) {
            updateMove(ui, divToMove, btnUpdate, txtCtrlName);
            isMoving = false;
        }
        });
    }
}


function AutoRoll() {
    //This does rollovers for class AutoRoll using on and off attributes
    $('.AutoRoll').hover(
        function () {
            var img = $(this).attr('on')
            $(this).attr('src', img)
        }
        ,
        function () {
            var img = $(this).attr('off')
            $(this).attr('src', img)
        }

        );

}

// *********** Editor ******************************

function DeleteEd(divName, txtName) {
    StoreEditorName(divName, txtName);
    $('#' + txtName).val('');
    Notify('NotChanged');
    UpdateDivEditor();
    return false;
}

function SetEditorTextRaw(val) {
    $('#' + lastTxtName).val(val);
    Notify('Changed');
}

function SetEditorTextHTML(val) {
    $('#' + lastDivName).html(val);
}

function Notify(msg) {
    var chgName = $('#' + lastDivName).attr('chg')
    $('#' + chgName).html(msg);
}

function UpdateDivEditor() {
    SetEditorTextHTML($('#' + lastTxtName).val());
}

function UpdateTextEditor() {
    SetEditorTextRaw($('#' + lastDivName).html());
    Filter();
}

function Filter() {
    var html = $('#' + lastTxtName).val();
    html = html.replace("border-top-width: 1px;", "");
    html = html.replace("border-right-width: 1px;", "");
    html = html.replace("border-bottom-width: 1px;", "");
    html = html.replace("border-left-width: 1px;", "");
    html = html.replace("border-top-style: none;", "");
    html = html.replace("border-right-style: none;", "");
    html = html.replace("border-bottom-style: none;", "");
    html = html.replace("border-left-style: none;", "");
    html = html.replace("cursor: pointer;", "");

    SetEditorTextRaw(html);
}

function SelPageEd(page, nw) {
    if (fileMode == 'roll') {
        $('#txtR3').val(page);
    }
    else {
        if (nw)
            htmlEd("link", "a", lastDivName, lastTxtName, " target='_blank'  href='" + page + "'", "click here");
        else
            htmlEd("link", "a", lastDivName, lastTxtName, "  href='" + page + "'", "click here");
    }
}


function MakeRollover() {
    var img1 = 'CustomImages/' + $('#txtR1').val();
    var img2 = 'CustomImages/' + $('#txtR2').val();
    var page = $('#txtR3').val();
    var blank = '';
    var onoff = " on='" + img2 + "' off='" + img1 + "' class='AutoRoll'  src='" + img1 + "' class='PosIt' ";
    var nw = $('#chkR4').attr('checked');
    var absolute = $('#chkR5').attr('checked');

    if (nw)
        blank = " target='_blank' "

    if (page == '') {
        htmlEd("img", "img", lastDivName, lastTxtName, onoff, "");
    }
    else {
        htmlEd("linkimg", "a", lastDivName, lastTxtName, " class='PosIt' href='" + page + "' " + blank, "<img " + onoff + " border='0' />");
    }

    if (absolute) {
        SetupMovableObjects();
    }

    return false;
}
function HideRollOverPop() {
    $('#roll').css({ 'display': 'none' });
    return false;
}
function SelFileEd(file) {
    if (fileMode == 'roll') {
        if (rolTxtNo == 1) {
            $('#txtR1').val(file);
            $('#r1').attr('src', 'customimages/' + file);
        }
        else {
            $('#txtR2').val(file);
            $('#r2').attr('src', 'customimages/' + file);
        }
    }
    else {
        htmlEd("img", "img", lastDivName, lastTxtName, "  class='PosIt' src='customimages/" + file + "'", "");
        SetupMovableObjects();
    }
    return false;
}


function htmlEd(cmd, value, divName, txtName, attrib, content) {
    RestoreFocusAfterCmd();
    editorPass = false;
    StoreEditorName(divName, txtName);

    switch (cmd) {
        case 'fld':
            SurroundWithBracket(value, attrib, content, true);
            editorPass = true;
            break;
        case 'link':
        case 'enter':
        case 'div':
        case 'fcolor':
        case 'para':
        case 'bis':
            //            alert('aqqqqa111111111');
            if (RemoveCloseElement(value, cmd, attrib)) {
                editorPass = true;
            }
            else {
                editorPass = SurroundWith(value, attrib, content);
            }
            break;
        case 'ul':
            editorPass = Buttons(cmd);
            break;
        case 'ol':
            editorPass = Buttons(cmd);
            break;
        case 'linkimg':
        case 'img':
            SurroundWith(value, attrib, content, true);
            editorPass = true;
        case 'upd':
            editorPass = true;
            break;
        case 'rf':
            editorPass = true;
            ClearFormatting();
            break;
    }

    if (editorPass) {
        $('#txtContentUndo').val($('#' + txtName).val());
        SetEditorTextRaw($('#' + divName).html());
    }
    else {
        if (cmd == 'key') {

            $('#txtContentUndo').val($('#' + txtName).val());
            SetEditorTextRaw($('#' + divName).html());
        }
        else {
            alert('Please select some text first')
        }
    }


    //alert('HTMLED end');
    // RestoreFocusAfterCmd();
    if (cmd == 'key')
        return true;
    else
        return false;
}

function handleEnterEdDown(event) {
    var keyCode = event.which;
    if (keyCode == undefined) {
        keyCode = event.keyCode;
    }
    if (keyCode != undefined) {
        if (keyCode == 13 && event.shiftKey == false) {
            if (!window.ActiveXObject) {
                window.event.cancelBubble = true;
                return false;
            }
        }
    }

    return true;
}




function handleEnterEdUp(event, divName, txtName) {
    // if ($('.eol')) {
    //$('.eol').remove();


    // }
    var keyCode = event.which;
    if (keyCode == undefined) {
        keyCode = event.keyCode;
    }
    if (keyCode != undefined) {
        if (keyCode == 13 && event.shiftKey == false) {
            if (!window.ActiveXObject) {
                var last = '';
                var node = SetSelectedText("<br/><br id='eol'/>");
                CaretSetToEnd('eol');
                window.setTimeout('RemoveBR()', 100);

                return false;
            }
        }
    }

    return htmlEd('key', '', divName, txtName);

}

function SetEDFocus(divName) {
    var editableDiv = $('#' + divName)[0];
    editableDiv.focus();
}

function CaretSetToEnd(divName) {
    var editableDiv = $('#' + divName)[0];
    editableDiv.focus();
    CaretSetToEndBase(editableDiv);
}

function CaretSetToEndBase(el) {
    var sel, range;
    if (window.getSelection && document.createRange) {
        range = document.createRange();
        range.selectNodeContents(el);
        HilightRange(range);
    }
    else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(el);
        HilightRange(range);

    }
}



function InitialiseMoveSizePanel() {
    var top, left, width, hgt;
    var pos = $('#' + lastDivName).position();
    var scrollTopVal = $('#' + lastDivName).attr('scrollTop');
    var scrollLeftVal = $('#' + lastDivName).attr('scroll');
    if (scrollTopVal == undefined)
        scrollTopVal = 0;
    if (scrollLeftVal == undefined)
        scrollLeftVal = 0;

    top = pos.top + scrollTopVal;
    left = pos.left + scrollLeftVal;
    width = $('#' + lastDivName).width();
    hgt = $('#' + lastDivName).height();
    $('#PosGrid').css({ 'top': top, 'left': left, 'width': width, 'height': hgt, 'display': 'none' });


}

function SetupMovableObjects() {
    var pass = false;
    RMenu();
    $('.PosIt').css({ 'position': 'absolute' });
    $('.PosIt').css({ 'cursor': 'pointer' });


    $('.PosIt').hover(
            function () {
                $(this).css({ 'border-style': 'solid', 'border-width': '1px' });
            },
            function () {
                $(this).css({ 'border-style': 'none' });
            }
        );

    return pass;
}


function updateMoveEd(ui) {
    htmlEd('upd', '', lastDivName, lastTxtName);
}

function StoreEditorName(divName, txtName) {
    lastDivName = divName;
    lastTxtName = txtName;
}


function RGBColorEd(divName, txtName) {
    var rgb = prompt('Type a RGB Colour, eg. 50,50,50', '0,0,0');
    htmlEd('fcolor', 'span', divName, txtName, 'style="color:rgb(' + rgb + ');"');
    return false;
}

function colorEd(cboCombo, divName, txtName) {
    var color = GetComboVal(cboCombo, true);
    htmlEd('fcolor', 'span', divName, txtName, 'style="color:' + color + '"');
    return false;
}

function RGBColorBEd(divName, txtName) {
    var rgb = prompt('Type a RGB Colour, eg. 50,50,50', '0,0,0');
    htmlEd('fcolor', 'span', divName, txtName, 'style="background-color:rgb(' + rgb + ');"');
    return false;
}

function colorBEd(cboCombo, divName, txtName) {
    var color = GetComboVal(cboCombo, true);
    htmlEd('fcolor', 'span', divName, txtName, 'style="background-color:' + color + '"');
    return false;
}

function paraChange(cboCombo, divName, txtName) {
    var para = GetComboVal(cboCombo, true);
    if (para == 'DateTime')
        htmlEd("para", "div", divName, txtName, " class='datetime' ");
    else
        htmlEd('para', para, divName, txtName);

    return false;
}

function formatCurrency(num) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    return parseFloat(num).toFixed(2);
}

function fieldInsert(cboCombo, divName, txtName) {
    var val = GetComboVal(cboCombo, true);
    htmlEd('fld', val, divName, txtName);
    return false;
}

function GetComboVal(cboCombo, reset) {
    var dropdown = document.getElementById(cboCombo);
    var index = dropdown.selectedIndex;
    var ddVal = dropdown.options[index].value;
    if (reset)
        dropdown.selectedIndex = 0;

    return ddVal;
}


function UndoHtmlEd(divName, txtName) {
    StoreEditorName(divName, txtName);
    SetEditorTextRaw($('#txtContentUndo').val());
    SetEditorTextHTML($('#txtContentUndo').val());
    return false;
}



function ToggleHTML(divName, txtName) {
    StoreEditorName(divName, txtName);
    if ($('#' + divName).css('display') == 'none') {
        SetEditorTextHTML($('#' + txtName).val());
        $('#' + divName).css({ 'display': 'block', 'width': '100%', 'height': '100%' })
        $('#' + txtName).css({ 'display': 'none' })
        SetupMovableObjects();
    }
    else {
        $('#' + txtName).val($('#' + divName).html());
        $('#' + divName).css({ 'display': 'none' })
        $('#' + txtName).css({ 'display': 'block', 'width': '100%', 'height': '100%' })
        UpdateTextEditor();

    }

    return false;
}

function IsTextSelected(text) {
    var pass = false;
    if (text) {
        if (text != '|empty|') {
            if (text != '') {
                pass = true;
            }
        }
    }
    if (pass == false)
        alert('Please select some text first.');

    return pass;
}

function InsertDiv(divName, txtName) {
    StoreEditorName(divName, txtName);
    var obj = GetSelectedText();
    if (IsTextSelected(obj)) {
        var text = obj.toString();
        SetSelectedText('&nbsp;');
        UpdateTextEditor();
        var html = $('#' + lastTxtName).val();
        html += "<div class='PosIt' style='position:absolute;display:block;width:100px;height:100px;top:10px;left:100px;' >" + text + "</div>";
        SetEditorTextRaw(html);
        UpdateDivEditor();
        SetupMovableObjects();
    }

    return false;
}


function SurroundWithBracket(value, attrib, content, noSelectionNeeded) {
    if (value != 'None')
        SetSelectedText("{" + value + "}");

    return true;
}

function SurroundWith(value, attrib, content, noSelectionNeeded) {
    var pass = false;
    var text = GetSelectedHTML();
    //var text = GetSelectedText();

    //    alert('Surround Start ' + value + ' - ' + attrib + ' - ' + content + ' txt=' + text);
    if (text != '|empty|' || noSelectionNeeded) {
        if (text != '' || noSelectionNeeded) {
            pass = true;

            if (text.indexOf('<' + value) != -1) {
                ClearFormatting();
                text = GetSelectedText();
            }

            if (attrib == undefined) {

                if (content == undefined)
                    SetSelectedText("<" + value + ">" + text + "</" + value + ">");
                else
                    SetSelectedText("<" + value + ">" + content + text + "</" + value + ">");
            }
            else {

                if (content == undefined)
                    SetSelectedText("<" + value + " " + attrib + ">" + text + "</" + value + ">");
                else
                    SetSelectedText("<" + value + " " + attrib + ">" + content + text + "</" + value + ">");

            }

        }

    }

    //alert('Surround End');

    return pass;

}

function GetRangeHtml(range) {
    if (window.getSelection) {
        var clonedSelection = range.cloneContents();
        var div = document.createElement('div');
        div.appendChild(clonedSelection);
        return div.innerHTML;
    } else if (document.selection) {
        // Explorer selection, return the HTML
        var text = TrimOffIfFirstElemnt(range.htmlText);
        return text;
    }
    else {
        return '';
    }
}

function TrimOffIfFirstElemnt(inText) {
    var text = jQuery.trim(inText)
    if (text.length > 0) {
        var firstElmHere = text.indexOf('<');
        if (firstElmHere == 0) {
            var secElmHere = text.indexOf('>');
            if (secElmHere < 8) {
                if (secElmHere != -1) {
                    text = text.substring(secElmHere + 1);
                    var here2 = text.lastIndexOf('<');
                    if (here2 != -1)
                        text = text.substring(0, here2);

                    inText = text;
                }
            }
        }
    }

    return inText;
}

function GetSelectedHTML() {
    var range = GetSelectionRange();
    return GetRangeHtml(range);
}

function GetSelectedText() {
    if (window.getSelection) {
        // Firefox, Opera, Google Chrome and Safari
        var range = window.getSelection();
        return range.toString();
    }
    else {
        if (document.selection.createRange) {        // Internet Explorer
            var range = document.selection.createRange();
            return range.text;
        }
    }
}

function GetRangeText(range) {
    if (window.getSelection)
        return range.toString();
    else
        return range.text;

}

function closeFUPopup() {

}

function dragMe(isImage) {

    InitialiseMoveSizePanel();
    var top, left;
    var pos = lastObjTomove.position();
    var width = lastObjTomove.width();
    var hgt = lastObjTomove.height();
    var image = '';
    var block = '';
    $('#blockMove').css({ 'display': 'none' });
    $('#blockResize').css({ 'display': 'none' });

    if (posMode == 'delete') {
        lastObjTomove.attr('class', 'deleteme');
        lastObjTomove.parent().empty('.deleteme');
        lastObjTomove = null;
        posMode = 'move';
        UpdateTextEditor();
        $('#PosGrid').css({ 'display': 'none' });
        return false;
    }

    block = '#block'

    $('#posEdit').empty();
    $('#posEdit').append("<img id='block'  src='images/bg_dg.jpg' style='position:absolute;display:none;'>");
    $('#block').dblclick(
               function () {
                   ClosePosGrid();
               });
    //.removeAttr("height").css({ width: "", height: "" });

    if (isImage) {
        image = lastObjTomove.attr('src');
        $(block).attr('src', image);

    }
    else {
        $(block).attr('src', 'images/bg_dg.jpg');
    }

    $('#PosGrid').css({ 'display': 'block' });
    $(block).css({ 'position': 'absolute', 'display': 'block', 'top': pos.top, 'left': pos.left, 'width': width, 'height': hgt })

    if (posMode == 'move') {
        $(block).css({ 'cursor': 'move' });
        $(block).draggable({ stop: function (event, ui) {
            var pos2 = $(block).position();
            lastObjTomove.css({ 'top': pos2.top, 'left': pos2.left });
            UpdateTextEditor();
            $(block).removeAttr("style");
            $('#PosGrid').css({ 'display': 'none' });
        }
        });
    }
    else {
        $(block).resizable({ handles: "all", ghost: false, autoHide: true, stop: function (event, ui) {
            $(block).css({ 'cursor': 'auto' });
            var width2 = $(block).css('width');
            var hgt2 = $(block).css('height');
            lastObjTomove.css({ 'width': width2, 'height': hgt2 });
            UpdateTextEditor();
            $(block).removeAttr("style");
            $('#PosGrid').css({ 'display': 'none' });

        }
        }); ;
    }

    $(block).hover(
                function () {
                    $(this).css({ 'border-style': 'solid', 'border-width': '1px' });
                },
                function () {
                    $(this).css({ 'border-style': 'none' });
                }
            );
}



function ClosePosGrid() {
    $('#PosGrid').css({ 'display': 'none' });
    return false;
}

function ParaReturnText() {
    var txt = $('#editPara').val();
    //txt = return2br(txt);
    //txt = txt.replace(/n/g,"");
    txt = txt.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')
    SetSelectedText('<p>' + txt + '</p>&nbsp;');
    UpdateTextEditor();
    return false;
}

function return2br(dataStr) {
    // return dataStr.replace(/[\r\n]/g, "<br />");
    return dataStr.replace("\r", "<br />");
}

function PosGridMode(mode, el) {
    posMode = mode;
    lastObjTomove = null;
    lastObjTomove = $(el);

    if (lastObjTomove.attr('src') == undefined)
        lastObjTomoveIsImage = false;
    else
        lastObjTomoveIsImage = true;

    dragMe(lastObjTomoveIsImage);

    return false;
}
function format() {
    var event = document.forms[0].elements[0].value;
    event = event.replace(/\n/g, '&lt\;br \\&gt\;');
    var day = 1;
    document.getElementById("input").innerHTML = "entry[" + day + "]=\"" + event + "\";";
}

function RMenu() {
    $(".PosIt").contextMenu({
        menu: 'myMenu'
    },
					function (action, el, pos) {
					    PosGridMode(action, el);

					});


}

function setCursor(node, pos) {
    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;

    if (!node) {
        return false;
    } else if (node.createTextRange) {
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    } else if (node.setSelectionRange) {
        node.setSelectionRange(pos, pos);
        return true;
    }

    return false;
}

function SetRangeText(range, html) {

    if (window.getSelection) {

        range.deleteContents();
        // range.extractContents();
        lastNode = range.createContextualFragment(html);

        range.insertNode(lastNode);

        //if (selText.length > 1) {
        focusRange = range;
        RestoreFocusAfterCmd();

        // }
        return lastNode;

    }
    else {
        //range.collapse(true);
        //range.pasteHTML("");
        lastNode = range.pasteHTML(html);
    }

    return range;
}

function SetSelectedText(html) {
    html = html.toString();
    //var selText = GetSelectedText();
    var range = GetSelectionRange();
    SetRangeText(range, html)
    return range;
}

function InsertHTMLElm(sel, range, element, cssClass) {
    range.deleteContents();
    var br = document.createElement(element);
    if (cssClass != 'undefined' && cssClass != '') {
        br.setAttribute('class', cssClass);
    }
    //br = range.createContextualFragment("<br/>");
    range.insertNode(br);
    range.setEndAfter(br);
    range.setStartAfter(br);
    sel.removeAllRanges();
    sel.addRange(range);


}



function InsertHTMLElm2(sel, range, element) {
    range.deleteContents();
    //var br = document.createElement(element);
    var br = range.createContextualFragment(element);
    range.insertNode(br);
    range.setEndAfter(br);
    range.setStartAfter(br);
    sel.removeAllRanges();
    sel.addRange(range);

}

function GetUserSelection() {
    var userSelection;

    if (window.getSelection) {
        userSelection = window.getSelection();
    }
    else if (document.selection) {
        userSelection = document.selection.createRange();
    }
    return userSelection;
}



function CaretToNextChar() {
    if (document.selection) {        // Internet Explorer
        var myRange = document.selection.createRange();
        myRange.move("character", 1);
        myRange.select();
    }
}

function CaretToPrevChar() {
    if (document.selection) {        // Internet Explorer
        var myRange = document.selection.createRange();
        myRange.move("character", -1);
        myRange.select();
    }
}

function GetCaretPos() {
    var startpos = 0;
    var endpos = 0;
    if (document.getSelection) {
        var sel = window.getSelection().getRangeAt(0);
        startpos = sel.startOffset;
        endpos = sel.endOffset;
        //endpos = sel.getBoundingClientRect().left;
        //endpos = sel.getBoundingClientRect().width;

    } else {
        var range = document.selection.createRange();
        var rangeCopy = range.duplicate();
        rangeCopy.moveToElementText(obj);
        rangeCopy.setEndPoint('EndToEnd', range);
        startpos = rangeCopy.text.length - range.text.length;
        endpos = startpos + range.text.length;
    }
    return [startpos, endpos];
}


function enterKeyDownHandler(evt, divName) {

    return true;
}

function RemoveBR() {
    if ($('.eol'))
        $('.eol').remove();
}

function enterKeyUpHandler(evt, divName, txtName) {
    if ($('.eol'))
        $('.eol').removeAttr('class');
    saveSelection();
    htmlEd('key', '', divName, txtName);
    return true;
}


function KeyCheckBr() {

    var addedBr = false;
    // sel = GetSel();  //window.getSelection();
    if (window.getSelection && typeof window.getSelection != "undefined") {
        // sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            InsertHTMLElm(sel, range, 'br');
            CaretToNextChar();
            sel = window.getSelection();
            range = sel.getRangeAt(0);
            InsertHTMLElm(sel, range, 'br', 'eol');
            addedBr = true;
        }
    }
    else if (typeof document.selection != "undefined") {
        sel = document.selection;
        if (sel.createRange) {
            range = sel.createRange();
            range.pasteHTML("<br>");
            range.select();
            addedBr = true;
        }

    }

    return addedBr;

}

function enterKeyPressHandler(evt, divName, txtName) {
    var sel, range, br
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;

    if (charCode == 13) {
        if (KeyCheckBr()) {
            if (typeof evt.preventDefault != "undefined") {
                evt.preventDefault();
            } else {
                evt.returnValue = false;
            }

        }
        window.setTimeout('RemoveInvalidBR()', 1000);
    }
}

function RemoveInvalidBR() {
    var range = saveSelection2();
    $('.undefined').remove();
    restoreSelection(range);

}

function setCursor(node, pos) {
    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
    if (!node) {
        return false;
    } else if (node.createTextRange) {
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    } else if (node.setSelectionRange) {
        node.setSelectionRange(pos, pos);
        return true;
    }
    return false;
}

function saveSelection2() {
    var focusRange2;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            focusRange2 = sel.getRangeAt(0);
            //focusRange.setStart();
            return focusRange2;
        }
    } else if (document.selection && document.selection.createRange) {
        focusRange2 = document.selection.createRange();
        return focusRange2;
    }
    return null;
}

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            var d = new Date();
            // $('#zaq2').val('saved' + d);
            focusRange = sel.getRangeAt(0);
            //focusRange.setStart();
            return focusRange;
        }
    } else if (document.selection && document.selection.createRange) {
        focusRange = document.selection.createRange();
        return focusRange;
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            // $('#zaq2').val('restored');
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}
function ClearFormatting() {

    RestoreFocusAfterCmd();
    var text = GetSelectedText()
    SetSelectedText(text);

}

function getActiveText() {
    var sel = document.selection;
    var rng = sel.createRange();
    if (rng != null && (sel.type == "Text" || sel.type == "None"))
        var text = rng.text;
    if (rng != null && document.forms[0].message.createTextRange)
        document.forms[0].message.caretPos = rng.duplicate();
    //alert(text)
    return text;
}

function RestoreFocusAfterCmd() {

    //$('#' + lastDivName).focus();
    restoreSelection(focusRange)
    //$('#' + lastDivName).focus();
}


function EditorMouseUp(divName, txtName) {
    if ($('.eol'))
        $('.eol').removeAttr('class');
    saveSelection();
    StoreEditorName(divName, txtName);
    fileMode = 'editor';
    return true;
}

function EditorMouseOut(divName, txtName) {

    StoreEditorName(divName, txtName);
    fileMode = 'editor';
    return true;
}

function GetSelectionRange() {
    var range;
    if (window.getSelection) {    // W3C Ranges
        var userSelection = window.getSelection();
        // Get the range:
        if (userSelection.getRangeAt) {
            range = userSelection.getRangeAt(0);
        }
        else {
            range = document.createRange();
            range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
            range.setEnd(userSelection.focusNode, userSelection.focusOffset);
        }
    }
    else if (document.selection) {
        // Explorer selection, return the HTML
        range = document.selection.createRange();
    }
    return range;

}



function parentContainer(range) {
    if (window.getSelection)
        return range.commonAncestorContainer;
    else
        return range.parentElement()

}

function GetNextNode(node, endNode, skipChildren) {
    //if there are child nodes and we didn't come from a child node
    if (endNode == node) {
        return null;
    }
    if (node.firstChild && !skipChildren) {
        return node.firstChild;
    }
    if (!node.parentNode) {
        return null;
    }
    return node.nextSibling
         || getNextNode(node.parentNode, endNode, true);
}


// var userSelection = GetUserSelection();
//  range.setStart (userSelection.anchorNode.parentNode, userSelection.anchorOffset);
//  range.setEnd (userSelection.focusNode, userSelection.focusOffset);
//var oFragment = oRange.cloneContents();
//var oHello = oP1.firstChild.firstChild;
// var oWorld = oP1.lastChild;
// // range.moveEnd('character', 1);
// var oFragment = oRange.extractContents();
// document.body.appendChild(oFragment);
//oRange1.commonAncestorContainer.tagName
// //range.surroundContents(node);
//var linkNode = $(this.editor.body).find("a[href='#temp_url#']");
//range.setStartBefore(node)
// range.setEnd(elm,4);
/*
// Internet Explorer, Opera, Google Chrome and Safari
if (el.insertAdjacentHTML)
el.insertAdjacentHTML ("beforeBegin", html);
else {
var range = document.createRange();
var frag = range.createContextualFragment(html);
el.parentNode.insertBefore(frag, el);
}
*/

function GetSel() {
    if (window.getSelection) {
        return window.getSelection();
    }
    else {
        return document.selection;
    }
}

function ParentContainer(range) {

    if (window.getSelection)
        return range.commonAncestorContainer;
    else
        return range.parentElement();

}

function FirstSelectedNode() {
    if (document.selection)
        return document.selection.createRange().parentElement();
    else {
        var selection = window.getSelection();
        if (selection.rangeCount > 0)
            return selection.getRangeAt(0).startContainer.parentNode;
    }
}

function HilightRange(range) {
    var sel = GetSel();
    range.collapse(false);

    if (window.getSelection) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    else {
        range.select();
    }
}

function CheckEachStyle(range, elementTag, className, attrib) {

    var found = false;
    if (!found) found = EraseIfFoundNear(range, 'H1', elementTag, className, attrib);
    if (!found) found = EraseIfFoundNear(range, 'H2', elementTag, className, attrib);
    if (!found) found = EraseIfFoundNear(range, 'H3', elementTag, className, attrib);
    if (!found) found = EraseIfFoundNear(range, 'H4', elementTag, className, attrib);
    return found;
}

function GetPreviousSibling(n) {
    var count = 1;
    var x = n.previousSibling;
    while (x != null && x.nodeType != 1) {
        x = x.previousSibling;
        count++;
        if (count > 100)
            break;
    }
    return x;
}

function EraseIfFoundNear(range, element, replaceWith, className, attrib) {
    var found = false;

    var pNode = ParentContainer(range);
    //var cursorStart = range.startContainer;
    //var html = GetRangeHtml(range);

    if (window.getSelection) {
        if (element == pNode.parentNode.tagName) {
            StripOut(pNode.parentNode, replaceWith, className, attrib);
            found = true;
        }
    } else {
        if (element == pNode.tagName) {
            StripOut(pNode, replaceWith, className, attrib);
            found = true;
        }
    }

    return found;
}

function CreateRange() {
    if (window.getSelection)
        return document.createRange();
    else
        return document.selection.createRange();
    //var r = document.body.createTextRange(); 

}

function PositionRangeToNode(range, node) {
    if (window.getSelection) {
        range.selectNode(node);
    }
    else {
        range.moveToElementText(node);
        range.select();
    }

}

function FindElms(parentNode, toNode) {

    var elms = parentNode.getElementsByTagName("*");
    for (i in elms) {
        if (elms[i].tagName != null) {
            alert(elms[i].tagName);
        }
    }


}

function StripOut(node, replaceWith, className, attrib) {

    var replaceWithElm = null;

    if (replaceWith != '') {
        replaceWithElm = document.createElement(replaceWith);
        if (className != null)
            replaceWithElm.className = className;
        if (attrib != null)
            replaceWithElm.style = attrib;

    }

    if (window.getSelection) {
        var rangeObj = document.createRange();
        rangeObj.selectNodeContents(node);
        var documentFragment = rangeObj.cloneContents();
        var parent = node.parentNode;
        if (replaceWith != '') {
            replaceWithElm.appendChild(documentFragment);
            parent.insertBefore(replaceWithElm, node);
            parent.removeChild(node);
        }

    }
    else {

        var rangeObj2 = CreateRange();
        PositionRangeToNode(rangeObj2, node);
        var html = GetRangeHtml(rangeObj2);
        html = "<" + replaceWith + ">" + html + "</" + replaceWith + ">"
        rangeObj2.pasteHTML(html);
        // HilightRange(n);

    }


}

function Buttons(prefix) {
    var html = GetSelectedHTML();
    html = html.replace(/<br>/gi, '</li><li>');
    html = '<' + prefix + '><li>' + html + '</li></' + prefix + '>'
    SetSelectedText(html);
    return true;
}

function RemoveCloseElement(elementTag, cmd, attrib) {
    var found = false;
    var range = GetSelectionRange();
    var className = null;
    elementTag = elementTag.toUpperCase();
    var st = range.startContainer

    switch (elementTag) {
        case 'SPAN':
            //found = EraseIfFoundNear(range, 'SPAN', elementTag, className, attrib);
            break;
        case 'DIV':
            className = 'DateTime';
            found = CheckEachStyle(range, elementTag, className, attrib);
            break;
        case 'X':
            found = CheckEachStyle(range, '', className, attrib);
            found = true;
            break;
        case 'H1':
        case 'H2':
        case 'H3':
        case 'H4':
            found = CheckEachStyle(range, elementTag, className, attrib);
            break;
        default:
            // found = EraseIfFoundNear(range, elementTag, attrib);
            break;
    }

    RestoreFocusAfterCmd();
    return found;

}

function IncCount(videoGuid, vid) {

    var dataParam = AddParam('videoGuid', videoGuid);
    CallAjaxOnServer('UpdateVideoCount', dataParam, 'ViewsFinishCountUpdate', vid);

}

function ViewsFinishCountUpdate(msg, vid) {
    $('#' + vid).html(msg);
}

function BringToFront(ctrl, pid) {
    if (lastZPara != '')
        $('#' + lastZPara).css({ 'opacity': '0.4', 'border-style': 'solid', 'border-width': '1px' });
    var zindex = GetZIndex();
    document.getElementById(ctrl).style.zIndex = zindex;
    $('#' + ctrl).css({ 'opacity': '1', 'border-style': 'solid', 'border-width': '1px' });
    //document.getElementById(lastFUCtrl).style.zIndex = zindex + 1;
    lastZPara = ctrl;
    var pname = document.getElementById("ZPName" + pid).value;
    document.getElementById("ZInx" + pid).value = zindex;
    var dataParam = AddAllParams(pid, zindex, pname);
    CallAjaxOnServer('UpdatePara', dataParam, 'ReturnSrvMsg', '');
}

function UpdateZndx(ctrl, pid) {
    if (lastZPara != '')
        $('#' + lastZPara).css({ 'opacity': '0.4', 'border-style': 'solid', 'border-width': '1px' });
    var zindex = document.getElementById("ZInx" + pid).value;
    document.getElementById(ctrl).style.zIndex = zindex;
    var left = document.getElementById("ZPLeft" + pid).value;
    var top = document.getElementById("ZPTop" + pid).value;
    var sleft = left + 'px';
    var stop = top + 'px';
    if(left=='')
        $('#' + ctrl).css({ 'opacity': '1', 'border-style': 'solid', 'border-width': '1px' });
    else
        $('#' + ctrl).css({ 'opacity': '1', 'border-style': 'solid', 'border-width': '1px','left':sleft,'top':stop });
    //document.getElementById(lastFUCtrl).style.zIndex = zindex + 1;
    lastZPara = ctrl;
    var pname = document.getElementById("ZPName" + pid).value;
    
    var dataParam = AddAllParams(pid, zindex, pname,null,null,left,top);
    CallAjaxOnServer('UpdatePara', dataParam, 'ReturnSrvMsg', '');
}

function ResizePara(pid, width, height) {
    var dataParam = AddAllParams(pid, empty, '', width, height);
    CallAjaxOnServer('UpdatePara', dataParam, 'ReturnSrvMsg', '');
}

function AddAllParams(pid, ZIndexChg, pname, width, height, left, top) {
    
    if (typeof ZIndexChg == "undefined")
        ZIndexChg = empty;

    if (typeof pname == "undefined")
        pname = '';

    if (width==null || typeof width == "undefined")
        width = empty;

    if (height==null || typeof height == "undefined")
        height = empty;

    if (typeof left == "undefined")
        left = empty;

    if (typeof top == "undefined")
        top = empty;


    var dataParam = AddParam('pid', pid, true);
    dataParam += AddParam('ZIndexChg', ZIndexChg, true);
    dataParam += AddParam('pname', pname, true);
    dataParam += AddParam('width', width, true);
    dataParam += AddParam('height', height, true);
    dataParam += AddParam('left', left, true);
    dataParam += AddParam('top', top);
    return dataParam;
}
function ToggleHide(ctrl, pid) {
    var obj = document.getElementById(ctrl);
    if (obj.style.display == 'block')
        obj.style.display = 'none';
    else
        obj.style.display = 'block';

    return false;
}


function ReturnSrvMsg(msg) {
    $('.cm').html(msg);
}

function SlideShow() {
    $('#slides').slides({
        preload: true,
        preloadImage: 'img/loading.gif',
        play: 5000,
        pause: 2500,
        hoverPause: true
    });

}

function FUPopupN(FUCtrl, positionCtrlName, title, global, width, height, left) {

    FUPopup(FUCtrl, '', title, global, width, height, left);
}

function ticker() {
   
        $('.tickL').mouseover(function () {
            $(this).stop();
        });
        $('.tickL').mouseout(function () {
            tickerStart();
        })
        $('.tickL').stop().css({ left: '1024px', display: 'block' });
        tickerStart();

       
}
function tickerStart() { 
 $('.tickL').animate({ left: -100 }, { easing: "linear", duration: 15000, complete: function () {
        window.setTimeout('ticker();', 1000);

    }});

}

function GetVideoInfo() {
    videoInfo.guid = $('#' + activeVideo).attr('vguid');
    videoInfo.vid = $('#' + activeVideo).attr('vc');
    videoInfo.songName = $('#' + activeVideo).attr('songname');
    videoInfo.zaps = $('#' + activeVideo).attr('zaps');
    videoInfo.viewed = parseInt($('#' + activeVideo).attr('viewed'));
   
    if ($('#' + activeVideo).attr('href2'))
        videoInfo.href = $('#' + activeVideo).attr('href2');
    else
        videoInfo.href = $('#' + activeVideo).attr('href');

    videoInfo.OncePlayed = $('#' + activeVideo).attr('fv');
}

function StartUpScript() {

    startUpScriptCount++;
    if (true) {
        $(window).ready(function () {
            SlideShow();
            fixCombos();
            if ($(".videolinkBig").length != 0) {
                $f(".videolinkBig", "flowplayer-3.2.5.swf", { clip: { autoPlay: true, autoBuffering: true} });
                $(".videolinkBig").click(function (i) {
                    //                    var guid = jQuery(this).attr('vguid')
                    //                    var href = jQuery(this).attr('href');
                    //                    var vid = jQuery(this).attr('vc');
                    //                    lastvGuid = guid;
                    //                  PlayClip('#MainVideoPlayer', href)
                    //                    IncCount(guid, vid);
                    return false;
                });
            }


            $(".videolink").click(function (i) {
                activeVideo = $(this).attr('id');
                PlayVideoNow(activeVideo);
                jQuery(this).attr('viewed', videoInfo.viewed);
                return false;
            });

            if (startUpScriptCount < 2) {
                InitVideo();
            }
            else {
                GetVideoInfo();
                SetupMainPlayer();
            }

            if (startUpScriptCount == 1)
                $('.DDMenu').dmDropDownMenu();

            var zindex = GetZIndex();
            $(".initButton").css({ position: 'relative', top: '0px', left: '0px', 'zIndex': zindex });
            $('.dgridrow').hover(function () { $(this).css({ 'background-color': '#C0C0C0' }); }
                         , function () { $(this).css({ 'background-color': '' }); }
                        );

            $('#frmViewPort').mousemove(function (e) {
                mouseX = e.pageX - $('#frmViewPort').offset().left;
                mouseY = e.pageY - $('#frmViewPort').offset().top;
                $('#test').html('X=' + mouseX + ' Y=' + mouseY);
            });

            $('.jtab').tabs();
            $('#marker').css({ opacity: '0' });

            $(function () {
                var zindex = GetZIndex();
                $(".jtab").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
                $(".jtab>div>ul>li").removeClass('ui-corner-top').addClass('ui-corner-left');
                $('.jtab>div:first').css({ position: 'relative', top: '0px', left: '0px', 'zIndex': zindex });
            });

            runEffect();
            AutoRoll();
            RMenu();

            //AnimatePage();
            ticker();

        });
    }
}

function PlayClip(player, videoInfo) {
    $f(player).close();
    if ($f(player).isLoaded()) {
        $f(player).getClip().update({ url: videoInfo.href });
    }
    else {
        $f(player).getClip(0).update({ url: videoInfo.href });
    }
    if (player == 'MainVideoPlayer')
        SetupMainPlayer();

    $f(player).play();
    lastvGuid = videoInfo.guid;

}

function InitVideo() {
    videoInfo.href='movies/flash/AfterVoting.flv';
    if ($('#MainVideoPlayer').length != 0)
        $f("MainVideoPlayer", { src: "flowplayer-3.2.5.swf", wmode: 'opaque' }, {

            plugins: {
                controls: {
                    autoHide: "never"
                }
            },

            clip: {
                
                onLastSecond: function () { //
                    if (OncePlayed == false) {
                        OncePlayed = true;
                        videoInfo.href = 'movies/flash/AfterVoting.flv';
                        PlayClip('MainVideoPlayer', videoInfo);
                    }
                    else {
                        $f("MainVideoPlayer").pause();
                    }
                }
            }

        }).ipad();

    }

    function PlayVideoNow(vguid) {
        OncePlayed = false;
        activeVideo = vguid;
        GetVideoInfo();
        videoInfo.viewed++;
        OncePlayed = false;

        if ($('#vidPlayer').length != 0)
            FUPopup('vidPlayer', '', 'Song', true, 490, 450);

        PlayClip('MainVideoPlayer', videoInfo)
        IncCount(videoInfo.guid, videoInfo.vid);
       
    }

    

    function PlayNow(vguid) {
       window.setTimeout('PlayVideoNow("' + vguid + '");',1000);

   }

   function StatusPoll(vguid) {
       window.setInterval("ping('" + vguid +"');", 4000);
   }

   function ping(videoGuid) {
       var dataParam = AddParam('videoGuid', videoGuid);
       CallAjaxOnServer('GetVideoStatus', dataParam, 'PingBack', '');
   }

   function PingBack(msg) {
       var d = new Date();
       if (msg == "") {
           $('#vidProg').html("Please upload your video now by clicking the 'Choose File' button below.");
       }
       else {
           $('#vidProg').html(msg + ' ' + d.toString());
           if (msg == 'Video Ready')
               location.reload(true);
       }
   }
