/**
*/
agent = navigator.userAgent.toLowerCase();
is_ie = ((agent.indexOf("msie") != -1) && (agent.indexOf("opera") == -1));
onloadActions = [];
function doPreview(eventTarget,dialogUrl){
    var saveReq=null;
	try{saveReq=isSaveRequired()}catch(e){};
	if (saveReq){
		showApplyChangesDialog(
		    function(useraction){
			    var canNavigate=true;
			    switch(useraction){
				    case 1:{
                        try{canNavigate=CheckData();}catch(e){}
				        if(canNavigate) __doPostBack(eventTarget,"true");
				    }break;
				    case 0:{
                        __doPostBack(eventTarget,"false");
				    }break;
			    }
		    }
		);
	}
	else{
        __doPostBack(eventTarget,"false");
	}
}

function ProcessOnloadActions() {
	Sb.isPageLoaded = true;
	
	for (var i = 0; i < onloadActions.length; ++i) {
		eval(onloadActions[i]);
	}
}

function RegisterOnloadAction(actionStr) {
	onloadActions.push(actionStr);
}

function doNavigate(url){
/*    try{onBeforeSaveReqCheck()}catch(e){};
    var saveReq = null;
	try{saveReq=isSaveRequired()}catch(e){};
	if (saveReq){
	   showApplyChangesDialog(
            function(useraction){
                var canNavigate=true;
                switch(useraction){
	                case 1:{
                        try{canNavigate=CheckData();}catch(e){}
	                    if(canNavigate) {
                            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(eventTarget, url+":true", true, "", PostBackUrl, false, true));
                            try{if (Page_ClientValidate && !Page_IsValid) setSaveRequired(true);}catch(e){};;
                        }
	                }break;
	                case 0:{
                            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(eventTarget, url+":false", false, "", PostBackUrl, false, true));
	                };break;
                }
            });

	}
	else{
        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(eventTarget, url+":false", false, "", PostBackUrl, false, true));
	}
	return false;
*/
    document.forms[0].action=url;
    document.forms[0].submit();
}

function doAdminNavigate(url) {
	document.forms['adminNavigation'].action = url;
    document.forms['adminNavigation'].submit();
}

function doFormNavigate(eventTarget,PostBackUrl){
    try{onBeforeSaveReqCheck()}catch(e){};
    var saveReq=null;
	try{saveReq=isSaveRequired()}catch(e){};
	if (saveReq){

		showApplyChangesDialog(
		    function(useraction){
			    var canNavigate=true;
			    switch(useraction){
				    case 1:{
                        try{canNavigate=CheckData();}catch(e){}
                        if (canNavigate) {
                            try{setSaveRequired(false);}catch(e){};
                            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(eventTarget, true, true, "", PostBackUrl, false, true));
                            try{if (Page_ClientValidate && !Page_IsValid) setSaveRequired(true);}catch(e){};;
                        }
				    }break;
				    case 0: {
                            try{setSaveRequired(false);}catch(e){};
                            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(eventTarget, false, false, "", PostBackUrl, false, true));
				    }break;
				    case -1:{
                       try{onApplyCanceled();}catch(e){}
				    };
			    }
		    }
		);
	}
	else{
        try{setSaveRequired(false);}catch(e){};
        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(eventTarget, false, false, "", PostBackUrl, false, true));
    }
    return false;
}


function openDialog(url, action, init) {
	if (typeof init == "undefined") {
		init = window;	// pass this window object by default
	}
	if (document.all) {	// here we hope that Mozilla will never support document.all
		var value = window.showModalDialog(url, init, "dialogHeight:150px; dialogWidth:320px; resizable: no; help: no; status: no; scroll: no; center: yes; ");
		if (action) {
			action(value);
		}
	} else {
		return openDialog._geckoOpenModal(url, action, init);
	}
};
openDialog._return = null;

openDialog._modal = null;

openDialog._arguments = null;

openDialog._geckoOpenModal = function(url, action, init) {
	var wnd =  window;
	var px = wnd.screenX + wnd.outerWidth;
	var py = wnd.screenY + wnd.outerHeight;
	var x = (px -320)/ 2;
	var y = (py-150) / 2;
	var dlg = window.open(url, "ha_dialog",
			      "location=no,directories=no,dialog=yes,modal=yes,toolbar=no,menubar=no,personalbar=no, sidebar=no,width=320,height=150," +
			      "scrollbars=no,resizable=no,status=no, outerWidth=320, outerHeight=150, left="+x+", top="+y);

	openDialog._modal = dlg;
	openDialog._arguments = init;

	function capwin(w) {
		w.addEventListener("click", openDialog._parentEvent, true);
		w.addEventListener("mousedown", openDialog._parentEvent, true);
		w.addEventListener("focus", openDialog._parentEvent, true);
	};

	function relwin(w) {
		w.removeEventListener("focus", openDialog._parentEvent, true);
		w.removeEventListener("mousedown", openDialog._parentEvent, true);
		w.removeEventListener("click", openDialog._parentEvent, true);
	};

	openDialog._return = function (val) {
		if ((val || val==0) && action) {
			action(val);
		}
		openDialog._modal = null;
	};
};

function sp2Detect(par){
	var mv=navigator.appMinorVersion;
	if(/sp2/i.test(mv)){
		return true;
	}else{
		return false;
	}
}

function validLink(temp){
	var str=temp;
	while(str.match(/http:([^\"]*?)\/preview/)!= null){
		str = str.replace(/http:([^\"]*?)\/preview/,".");
//"  !!!!! for colorers
	}
	return str;
}

var winStl = null;
var winProp = null;

function doCloseWindowProp(){
	try{
		winStl.close();
	}catch(e){
	}
	try{
		winProp.close();
	}catch(e){
	}
}

function checkSymbol (value, symbol)
{
	  var success = /[\';]/.test(value);
//'  !!!!! for colorers
	  return success;
}


function checkLengthofTextArea(obj,maxLength)
{
    var o;
	o=obj;

    if(o.value.length>maxLength)
	{
        o.value = o.value.substr(0, maxLength);
    }
    try{setSaveRequired(true);}catch(e){};
}

function doEncodeFields(arrayFields)
{
	var tempField = null;
	for(var i = 0; i < arrayFields.length; i++)
	{
		tempField = document.getElementsByName(arrayFields[i])[0];
		if(tempField) doEncodeField(tempField);
		tempField = null;
	}
}

function doEncodeField(field)
{
	var valueString = field.value;
	if(valueString == null) return false;
	valueString=valueString.replace(/&/ig,'&amp;');
	while(valueString.match(/</ig) != null){
        valueString=valueString.replace(/</ig,'&lt;');
    }
    while(valueString.match(/>/ig) != null){
        valueString=valueString.replace(/>/ig,'&gt;');
    }
    field.value = valueString;
}

function GridViewCheckAll(src,namePart){
	var ch=src.checked;
	var elt=document.getElementsByTagName("input");
	for(var i=0; i<elt.length; i++)
	{
		if(elt.item(i).type.toLowerCase()=='checkbox'  && elt.item(i).id.toLowerCase().indexOf(namePart.toLowerCase())>=0 && !elt.item(i).disabled) elt.item(i).checked=ch;
	}
}
function GridViewIsSelected(namePart){
	var elt=document.getElementsByTagName("input");
	for(var i=0; i<elt.length; i++)
	{
		if(elt.item(i).type.toLowerCase()=='checkbox'  && elt.item(i).id.toLowerCase().indexOf(namePart.toLowerCase())>=0 && !elt.item(i).disabled && elt.item(i).checked) {
		    return true;
		}
	}
	return false;
}
function GridViewSelectedCount(namePart){
	var elt=document.getElementsByTagName("input");
	count = 0;
	for(var i=0; i<elt.length; i++)
	{
		if(elt.item(i).type.toLowerCase()=='checkbox'  && elt.item(i).id.toLowerCase().indexOf(namePart.toLowerCase())>=0 && elt.item(i).checked) count++;
	}
	return count;
}

function EnableInputTextElement(namePart, valueNew){
	var elt=document.getElementsByTagName("input");
	for(var i=0; i<elt.length; i++)
	{
		if(elt.item(i).type.toLowerCase()=='text'  && elt.item(i).id.toLowerCase().indexOf(namePart.toLowerCase())>=0) {
		    elt.item(i).disabled = valueNew;
		}
	}
}

function GetDropDownListValue(namePart) {
	var elt=document.getElementsByTagName('select');
	for(var i=0; i<elt.length; i++)
	{
		if(elt.item(i).id.toLowerCase().indexOf(namePart.toLowerCase())>=0) {
		    return elt.item(i).value;
		}
	}

	return '';
}
minWidth = 1024;
minHeight = 614;

function checkAndResize(alertMessage) {

//    minWidth = 980;
//    minHeight = 600;

    agent = navigator.userAgent.toLowerCase();
    is_ie = ((agent.indexOf("msie") != -1) && (agent.indexOf("opera") == -1));

    windowWidth = document.documentElement.offsetWidth;
    windowHeight = document.documentElement.offsetHeight;
    if(windowWidth < minWidth || windowHeight < minHeight) {
        if (is_ie) {
            toolbarWidthAverage = 10;
            toolbarHeightAverage = 120;

            browserWidth = windowWidth + toolbarWidthAverage;
            if (browserWidth > screen.availWidth)
                browserWidth = screen.availWidth - 1;
            browserHeight = windowHeight + toolbarHeightAverage;
            if (browserHeight > screen.availHeight)
                browserHeight = screen.availHeight - 1;

            //window.detachEvent('onresize', checkAndResize);
            window.resizeTo(browserWidth, browserHeight);


            browserToolbarsHeight = browserHeight - document.documentElement.offsetHeight;
            browserToolbarsWidth = browserWidth - document.documentElement.offsetWidth;
            //resize to original size
            //window.detachEvent('onresize', checkAndResize);
            window.resizeTo(browserToolbarsWidth + windowWidth, browserToolbarsHeight + windowHeight);


            minBrowserWidth = browserToolbarsWidth + minWidth;
            minBrowserHeight = browserToolbarsHeight + minHeight;

        } else {
            //Firefox
            browserToolbarsHeight = window.outerHeight - window.innerHeight;
            browserToolbarsWidth = window.outerWidth - window.innerWidth;

            minBrowserWidth = browserToolbarsWidth + minWidth;
            minBrowserHeight = browserToolbarsHeight + minHeight;
        }

        if (minBrowserWidth > screen.availWidth || minBrowserHeight > screen.availHeight) {
                alert(alertMessage);
        }
        else {
            //window.detachEvent('onresize', checkAndResize);
            //resize to min values
            window.resizeTo(minBrowserWidth, minBrowserHeight);
        }
    }
}


function checkSize(alertMessage){
    windowWidth = document.documentElement.offsetWidth;
    windowHeight = document.documentElement.offsetHeight;
    if(windowWidth < minWidth || windowHeight < minHeight) {
        alert(alertMessage);
        if (is_ie) {
            window.detachEvent('onresize', checkBrowserSize);
        } else {
            window.removeEventListener('resize', checkBrowserSize, false);
        }
    }
}

function attachCheckToResize() {

    if (is_ie) {
        window.attachEvent('onresize', checkBrowserSize);
        window.attachEvent('onresize', resizeDivContent);
    }
    else {
        window.addEventListener('resize', checkBrowserSize, false);
        window.addEventListener('resize', resizeDivContent, false);
    }
}

function resizeDivContent() {
	var options = document.getElementsByName("inputResizeOption");
	for(var i = 0; i<options.length; i++) {
		var mheight;
		var name = "";
		var height = 200;
		if(/,/.test(options[i].value)) {
			var option = options[i].value.split(",");
			name = option[0];
			height = parseInt(option[1]);
		}
		var div = document.getElementById(name);
		if(div) {
			if (document.body.scrollHeight > document.body.clientHeight) {
				mheight = parseInt(document.body.scrollHeight);
			} else {
				mheight = parseInt(document.body.clientHeight);
				mheight = parseInt(window.innerHeight);
			}
			if (div.scrollHeight > (mheight-height)) {
				div.style.height=(mheight-height);
			} else {
				div.style.height = div.scrollHeight;
			}
		}
	}
}

function checkUrl(url, errorMessage){
    if (url.replace(/^\s+|\s+$/g,'')=='') return true;
    var v = new Validator();
    try {
        var res = v.verURL(url,3,false);
        if (!res)SetErrorMessage(errorMessage,true);
        return res;
    }
    catch(e){}
}

function trimStr(str) {
	return(str.replace(/(^\s*)|(\s*$)/g, ""));
}

function setElementVisibilty( elementID, isVisible, width )
{
	var el = document.getElementById( elementID );
	if ( is_ie )
		el.style.display = isVisible ? "block" : "none";
	else
		el.style.display = isVisible ? "inline" : "none";

	el.style.width = width;
	el.width = width;
}


function AdminPanelCheckToResize() {

    if (is_ie) {
        window.attachEvent('onresize', checkAdminPanelSize);
    }
    else {
        window.addEventListener('resize', checkAdminPanelSize, false);
    }
}

function checkAdminPanelSize() {	
	if ('none' != document.getElementById('adminPanelLeftMenu').style.display) {
		if (!!window.opera) {
			$('DivLeftMenu').style.height = '450px';
		} else {
			updateDivSize("DivLeftMenu", false);
		}
	}
	
    updateDivSize("DivAdminPanel",true);
}

function updateDivSize(id, changeWidth){
	// resizing doesn't work correctly under Opera
	if (!!window.opera) {
		return ;
	}
	
        var div = document.getElementById(id);
                
        var mheight,mwidth;
        
        if(div)
        {
            var iWidth=parseInt(div.scrollWidth);
            var iHeight=parseInt(div.scrollHeight);
            div.style.height=10;
            if (changeWidth) {
            	div.style.width=10;
            }

//alert(div.parentNode.offsetHeight);
            if(document.all)
            {
            	mheight = parseInt(div.parentNode.offsetHeight)-
                          parseInt(div.parentNode.currentStyle.paddingTop)-
                          parseInt(div.parentNode.currentStyle.paddingBottom);
                mwidth = parseInt(div.parentNode.offsetWidth)-
                          parseInt(div.parentNode.currentStyle.paddingLeft)-
                          parseInt(div.parentNode.currentStyle.paddingRight);
//str = '';
//for(var i in div.parentNode) {
//	str += i + ':' +  div.parentNode[i] + '\n<br>';
//}

//document.write(str);

            }
            else
            {
                mheight = parseInt(div.parentNode.offsetHeight);
                mwidth = parseInt(div.parentNode.offsetWidth);
                var p=div.parentNode;
                while (true){
                    if (!isNaN(parseInt(p.style.paddingBottom))){
                        mheight-=parseInt(p.style.paddingBottom);
                    }
                    if (!isNaN(parseInt(p.style.paddingTop))){
                        mheight-=parseInt(p.style.paddingTop);
                    }
                    if (!isNaN(parseInt(p.style.paddingLeft))){
                        mwidth-=parseInt(p.style.paddingLeft);
                    }
                    if (!isNaN(parseInt(p.style.paddingRight))){
                        mwidth-=parseInt(p.style.paddingRight);
                    }
                    if (!isNaN(parseInt(p.cellPadding))){
                        mheight-=2* parseInt(p.cellPadding);
                        mwidth-=2* parseInt(p.cellPadding);
                    }
                    if(p=='[object HTMLTableElement]') break;
                    else p=p.parentNode;
                }


            }
            if (iHeight> mheight)
            {
                div.style.height=mheight;
            }
            else
            {
                div.style.height = "100%";//div.scrollHeight;
            }

            if (changeWidth){
                //alert(div.scrollWidth);
                //alert(mwidth);
                if (iWidth> mwidth)
                {
                    div.style.width=mwidth;
                }
                else{
                    div.style.width="100%";
                }
                //alert(div.style.width);
            }

        }
}

function showElement(element, show) {
	if (show) {
		element.style.display = "";
	} else {
		element.style.display = "none";
	}
}

function isVisible(element) {
	return ('none' != element.style.display);
}

function openWizard(link) {
	if (top != self) {
		window.open(link);
	} else {
		window.location.href=link;
	}
}

function ShowAdminPanelNavigation() {
	// if we are not in the frame, so show navigation and header
	try {
		notInIframe = (top == self);
	} catch (e) {
		notInIframe = false;
	}
	
	if (notInIframe) {		
		adminPanelHeaderElement = document.getElementById('adminPanelHeader');
		adminPanelHeaderElement.style.display = '';
		
		adminPanelLeftMenuElement = document.getElementById('adminPanelLeftMenu');
		adminPanelLeftMenuElement.style.display = '';
	}
	
	// resize main content div
	AdminPanelCheckToResize();
	checkAdminPanelSize();
}

function SbWysiwygApplyChangesHandler(editorInstance) {
	if (SbGetApplyChangesObject().isSavingRequired()) {
		return ;
	}
	
	if (editorInstance.IsDirty()) {
		SbGetApplyChangesObject().registerChange();
	}
}

function FCKeditor_OnComplete(editorInstance) {
	editorInstance.ResetIsDirty();
	editorInstance.Events.AttachEvent('OnSelectionChange', SbWysiwygApplyChangesHandler);	
	
	SbOnFckSaveUndoStep(editorInstance);
}

function SbOnFckSaveUndoStep(editorInstance) {	
	editorInstance.EditorWindow.parent.FCKUndo._savedSaveUndoStep = editorInstance.EditorWindow.parent.FCKUndo.SaveUndoStep;
	
	editorInstance.EditorWindow.parent.FCKUndo.SaveUndoStep = function() {
		this._savedSaveUndoStep();
		SbGetApplyChangesObject().registerChange();
	}
}

function SbGetApplyChangesObject() {
	if ('undefined' == typeof self.sbApplyChangesObject) {
		return parent.sbApplyChangesObject;
	} else {
		return self.sbApplyChangesObject;
	}
}

function getFrameDocument(frameElement) {	
	var frameDoc = frameElement.contentWindow || frameElement.contentDocument;

	if (frameDoc.document) {
		frameDoc = frameDoc.document;
	}
	
	return frameDoc;
}

function modalWindowAutoResize(frame, dialogId) {
	var contentHeight = (is_ie) 
		? $(getFrameDocument(frame).body).scrollHeight
		: $(getFrameDocument(frame).body).getHeight();	
	var dialog = $(dialogId);
	
	if (!contentHeight) {
		return ;
	}
	
	$(frame).setStyle({ height : contentHeight + 'px' });	
	dialog.setStyle({ height : (contentHeight + dialog.verticalBorderHeight) + 'px' });
	
	// fix troubles with Mozilla scrolling behavior
	frame.contentWindow.scrollTo(0, 0);
	
	// force placing dialog to center
	dialog.hide();
	dialog.show();
}