﻿
// Find object(runat="server") which ClienID is stored in hidden field
function GetServerObject(id)
{
    var clientHiddenField = document.getElementById(id);
    return document.getElementById(clientHiddenField.value);
}

// correctly handle PNG transparency in Win IE 5.5 & 6.
function CorrectPNG()
{
    try 
    {
        var arVersion = navigator.appVersion.split("MSIE");
        var version = parseFloat(arVersion[1]);
        if ((version >= 5.5) && (document.body.filters))
        {
            for(var i=0; i<document.images.length; i++)
            {
                var img = document.images[i];
                var imgName = img.src.toUpperCase();
                if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
                {
                    var imgID = (img.id) ? "id='" + img.id + "' " : "";
                    var imgClass = (img.className) ? "class='" + img.className + "' " : "";
                    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
                    var imgStyle = "display:inline-block;" + img.style.cssText;
                    if (img.align == "left") 
                        imgStyle = "float:left;" + imgStyle;
                    if (img.align == "right") 
                        imgStyle = "float:right;" + imgStyle;
                    if (img.parentElement.href) 
                        imgStyle = "cursor:hand;" + imgStyle;
                    var filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader"
                        + "(src='" + img.src + "', sizingMethod='scale')";
                    var strNewHTML = "<span " + imgID + imgClass + imgTitle 
                        + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                        + "filter:" + filter + ";" + "\"></span>";
                    img.outerHTML = strNewHTML;
                    i = i-1;
                }
            }
        }
    } catch(E){ }
} 

//
// GetPageScrollArray()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function GetPageScrollArray()
{
	var yScroll, xScroll;
	if (self.pageYOffset) 
	{
		yScroll = self.pageYOffset;
	} 
	else if (document.documentElement && document.documentElement.scrollTop)
	{	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} 
	else if (document.body) 
	{   // all other Explorers
		yScroll = document.body.scrollTop;
	}

    if(window.pageXOffset)
    { 
	    xScroll=window.pageXOffset 
    } 
    else if(document.documentElement && document.documentElement.scrollLeft)
    { 
	    xScroll=document.documentElement.scrollLeft; 
    } 
    else if(document.body)
    { 
	    xScroll=document.body.scrollLeft; 
    }

	var arrayPageScroll = new Array(xScroll, yScroll) 
	return arrayPageScroll;
}

function RestoreScrollPosition()
{
    window.onscroll = scrollHandler;
    var scrollTop = $get(hidScrollTopId).value;
    if (scrollTop != "")
        document.documentElement.scrollTop = scrollTop;
}

function Show(ID)
{
    var window = document.getElementById(ID);
    window.style.display = "";


}
function Close(ID)
{
    var window = document.getElementById(ID);
    window.style.display = "none";

}
//
// GetPageSizeArray()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
//
function GetPageSizeArray()
{
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) 
	{	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} 
	else if (document.body.scrollHeight > document.body.offsetHeight)
	{   // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} 
	else 
	{   // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) 
	{	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} 
	else if (document.documentElement && document.documentElement.clientHeight) 
	{   // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} 
	else if (document.body) 
	{   // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight)
	{
		pageHeight = windowHeight;
	} 
	else 
	{ 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth)
	{	
		pageWidth = windowWidth;
	} 
	else 
	{
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getWindowSize() {
    var w=0;
    var h=0;
    if( document.documentElement && ( document.documentElement.scrollWidth || document.documentElement.scrollHeight )) {
         if ((document.body.scrollHeight>document.documentElement.scrollHeight) || (document.body.scrollWidth>document.documentElement.scrollWidth)) {
              return {w:document.body.scrollWidth, h:document.body.scrollHeight};
         }
         return {w:document.documentElement.scrollWidth, h:document.documentElement.scrollHeight};
    } else if( typeof( window.innerWidth ) == 'number' ) {
         return {w:window.innerWidth, h:window.innerHeight};
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
         return {w:document.body.clientWidth, h:document.body.clientHeight};
    }
    return {w:0, h:0};
}

function GetWindowInnerSize()
{
	if (window.innerWidth)  // non-IE
		return {width: window.innerWidth, height: window.innerHeight};
	else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))  // IE 6+ in 'standards compliant mode'
		return {width: document.documentElement.clientWidth, height: document.documentElement.clientHeight};
	else if (document.body && (document.body.clientWidth || document.body.clientHeight))  // IE 4 compatible
		return {width: document.body.clientWidth, height: document.body.clientHeight};
}


// show/hide flash content
function ShowOrHideFlashContent(idSuff, flashOk)
{
    if (document.getElementById('pnlFlashPresent' + idSuff) == null)
        return false;

    if (flashOk)
        document.getElementById('pnlFlashPresent' + idSuff).style.display = 'block';
    else
        document.getElementById('pnlNoFlash' + idSuff).style.display = 'block';

    return true;
}

var mediaObjectsCountId = null;

// Check flash version and show/hide flash content
function CheckFlashVersion()
{
    if (typeof(DetectFlashVer) == 'undefined' || mediaObjectsCountId == null)
        return;

    var flashOk = DetectFlashVer(9, 0, 0);

    ShowOrHideFlashContent('', flashOk);

    var mediaObjectsCount = document.getElementById(mediaObjectsCountId).value;

    for (var n = 0; n < mediaObjectsCount; n++)
        ShowOrHideFlashContent(n, flashOk);
}

window.currentElementFocus = null;

// Store caret
// text - textbox that have focus
function StoreCaret(text)
{
        // Only bother if it will be useful.
        if (typeof(text.createTextRange) != 'undefined')
            text.caretPos = document.selection.createRange().duplicate();
        window.currentElementFocus = text;
}

// Add text at saved caret position
// text - text to insert
function AddTextAtSavedPosition(text)
{
    var focusedElement = window.currentElementFocus;
    if (focusedElement == null)
        return;
    
    if (typeof(focusedElement.InsertHtml) == 'function')
    {
        focusedElement.InsertHtml(text);
    }
    else
    {
        InsertTextToTextArea(focusedElement, text)
    }
    
}

// insert text to text area
function InsertTextToTextArea(textarea, text)
{
    if (typeof(textarea.caretPos) != 'undefined' && textarea.createTextRange)
    {
        var caretPos = textarea.caretPos;

        caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
        caretPos.select();
    }
    // Mozilla text range replace.
    else if (typeof(textarea.selectionStart) != 'undefined')
    {
        var begin = textarea.value.substr(0, textarea.selectionStart);
        var end = textarea.value.substr(textarea.selectionEnd);
        var scrollPos = textarea.scrollTop;

        textarea.value = begin + text + end;

        if (textarea.setSelectionRange)
        {
            textarea.focus();
            textarea.setSelectionRange(begin.length + text.length, begin.length + text.length);
        }
        textarea.scrollTop = scrollPos;
    }
    // Just put it on the end.
    else
    {
        textarea.value += text;
        textarea.focus(textarea.value.length - 1);
    }
}

// *********************************** FCKEditor related ************************************
var fckPluginWindows = [];

function CloseFCKPluginWindows()
{
    for (var n in fckPluginWindows)
        if (typeof(fckPluginWindows[n]) == "object")
        {
            try
            {
                fckPluginWindows[n].close();
            }
            catch (e)
            {}
        }
                
    fckPluginWindows.length = 0;
}

function ClosePopupWindowWithFCK()
{
    CloseFCKPluginWindows();
    ClosePopupWindow();
}

var fckUniqueIds = [];

function FCKUniqueID(name, guid)
{
    this.name = name;
    this.guid = guid;
}

function GetFCKUniqueID(name)
{
	for (var n in fckUniqueIds)
		if (fckUniqueIds[n].name == name)
			return fckUniqueIds[n].guid;

	return null;
}

function OnFCKEditorSelectionChange(editorInstance)
{
	var toolbarItem = editorInstance.EditorWindow.parent.FCKToolbarItems.LoadedItems['EditScreenshot'];

	if (toolbarItem._UIButton != null)
	{
        	var selectedElem = editorInstance.EditorWindow.parent.FCKSelection.GetSelectedElement();

		if (selectedElem != null && selectedElem.nodeType == 1 && selectedElem.nodeName.toLowerCase() == "img" &&
		 selectedElem.getAttribute('id') != null && selectedElem.getAttribute('id').indexOf('UploadedByFCK_') == 0 &&
                 (selectedElem.getAttribute('mediatype') == null || selectedElem.getAttribute('mediatype') == 2))
			toolbarItem.Enable();
		else
			toolbarItem.Disable();
	}
}

function FCKeditor_OnComplete(editorInstance)
{
	var toolbarItem = editorInstance.EditorWindow.parent.FCKToolbarItems.LoadedItems['EditScreenshot'];
	if (toolbarItem._UIButton != null)
		toolbarItem.Disable();

	if (typeof(OnMediaUploaded) == 'function')
		editorInstance.Events.AttachEvent( 'MediaUploaded', OnMediaUploaded ) ;
	editorInstance.AttachToOnSelectionChange(OnFCKEditorSelectionChange);

	if (typeof(FCKeditor_OnComplete1) == 'function')
		FCKeditor_OnComplete1(editorInstance);
}

// ************************************* keyboard related ***********************************

function CallOnEnter(e, func)
{
    var keynum;
    
    if (window.event)
        keynum = e.keyCode;
    else if (e.which)
        keynum = e.which;
        
    if (keynum == 13)
    {
	func();
        return false;
    }

    return true;
}


// ************************************* submit related ***********************************

var submitRequestDone = false;
var submitRequest = false;
var popupRequestDone = false;
var popupRequest = false;
var popupWaitTimeoutId = -1;

var pageFullyLoaded = false;

/*function DisableControlsOnSubmit()
{
	for (var n in controlsToDisableOnSubmit)
	{
		var elem = document.getElementById(controlsToDisableOnSubmit[n]);
		elem.onclick = new Function("return false;");

		continue;
		var tagName = elem.nodeName.toLowerCase();
		
		if (tagName == "input")
		{
			var inputTypeName = elem.type.toLowerCase();

			if (inputTypeName == "button" || inputTypeName == "submit")
				elem.disabled = true;
		}
		else if (tagName == "button")
			elem.disabled = true;
	}
}*/

function OnFormSubmit()
{
	if (__CancelFormSubmit)
	{
		__CancelFormSubmit = false;
		return false;
	}
	else 
	{
		if (!pageFullyLoaded)
			return false;

		if (submitRequest)
		{
			submitRequestDone = true;
			submitRequest = false;

			//alert('submitRequestDone = true');
		}
		if (popupRequest)
		{
			popupRequestDone = true;
			popupRequest = false;

			popupWaitTimeoutId = setTimeout("location.reload()", 60000);
		}

		return true;
	}
}

function SetSubmitRequest(isPopupOpen)
{
	if (submitRequestDone || (isPopupOpen && popupRequestDone))
		return false;

	if (isPopupOpen)
	{
		popupRequest = true;
		submitRequest = false;
	}
	else
	{
		submitRequest = true;
		popupRequest = false;
	}

	return true;
}


// ************************************* miscellaneous **************************************

/*function OnCharacterTypeChanged(list, titleFormat, titleId)
{
	if (editCommentTitles == null)
		return;

	var titleElem = document.getElementById(titleId);
	var isIE = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
	var elems, ind1, ind2;

	if (isIE)
	{
		elems = list.childNodes[0].childNodes[0];
		ind1 = 0;
		ind2 = elems.childNodes.length;
	}
	else
	{       
	   	var elems = list.childNodes[1].childNodes[0];
		ind1 = 1;
		ind2 = elems.childNodes.length - 1;
	}
	
	for (var n = ind1; n < ind2; n++)
		if (elems.childNodes[n].childNodes[0].checked)
		{
			titleElem.innerHTML = titleFormat.replace('{0}', editCommentTitles[n - ind1]);
			//titleElem.innerHTML = titleElem.innerHTML;
			break;
		}
}
*/

function DoPostBackRedirect(redirectUrl)
{
	if (document.forms.length == 0)
		return;

	var form = document.forms[0];
	form.method = 'post';
	form.action = redirectUrl;
	
	if (form.__VIEWSTATE)
	{
		form.__VIEWSTATE.name = 'EMPTY_VIEWSTATE';
		form.__VIEWSTATE.value = '';
	}
	if (form.__EVENTTARGET)
		form.__EVENTTARGET.name = 'EMPTY_EVENTTARGET';
	if (form.__EVENTARGUMENT)
		form.__EVENTARGUMENT.name = 'EMPTY_EVENTARGUMENT';
	
	form.submit();
}


// **************************************** autosave ***********************************

var autoTriggerSecondsLeft = null;
var autoTriggerButtonClientId;
var autoTriggerButtonUniqueId;
var funcForCallingAfterAutosaveCompletion;
var lastAutosaveDate;
var autosavingIndicatorId;
var autosavePeriod;

function TryToMakeAutosave()
{
	if ($get(autoTriggerButtonClientId) != null && !submitRequestDone)
	{
		for (var fckEditorId in fckEditorFields)
		{
			var editorInstance = FCKeditorAPI.GetInstance(fckEditorId);
			if (editorInstance != null) 
			{
				try
				{
					$get(fckEditorFields[fckEditorId]).value = editorInstance.GetXHTML(true); 
				}
				catch (e)
				{}
			}
		}

		lastAutosaveDate = $get(hdnAutosaveDateId).value;
		$get(autosavingIndicatorId).style.display = 'block';
		__doPostBack(autoTriggerButtonUniqueId, '');
	}
}

function AutoTriggerButton()
{
	if (autoTriggerSecondsLeft != null && (autoTriggerSecondsLeft -= 10) <= 0)
	{
		TryToMakeAutosave();
		$get(hdnAutoTriggerSecondsLeftId).value = autoTriggerSecondsLeft;
		//autoTriggerSecondsLeft = null;
		autoTriggerSecondsLeft = autosavePeriod;
	}

	setTimeout('AutoTriggerButton()', 10000);
}

setTimeout('AutoTriggerButton()', 10000);

function CallFuncAfterAutosaveCompletion(func, seconds)
{
	if (seconds == null)
	{
		funcForCallingAfterAutosaveCompletion = func;
		CallFuncAfterAutosaveCompletion(null, 10);
	}
	else
	{
		if (lastAutosaveDate != $get(hdnAutosaveDateId).value || seconds == 0)
		{
			$get(autosavingIndicatorId).style.display = 'none';
			funcForCallingAfterAutosaveCompletion();
		}
		else
			setTimeout('CallFuncAfterAutosaveCompletion(null, ' + (seconds - 1) + ')', 1000);
	}
}


//alert(Sys.WebForms.PageRequestManager.getInstance());
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(TestEndRequestHandler);

/*function TestEndRequestHandler(sender, args)
{
	if (args.get_error() != null)
	{

		alert(args.get_response().getAllResponseHeaders());
		alert(args.get_response().get_responseData());
		args.set_errorHandled(true);
	}
}*/

// ******************************** validation ********************************

function IsFreeOrPriceValid(cbIsFreeId, txtPriceId, minimalPrice)
{
	var cbIsFree = $get(cbIsFreeId);
	if (cbIsFree == null || !cbIsFree.checked)
	{
		var price = parseFloat($get(txtPriceId).value);
		if (isNaN(price) || price < minimalPrice)
			return false;
	}


	return true;
}


// **************************** DateSelector *****************************

// dateType: 1 - all time, 2 - year, 3 - month, 4 - day
function DateSelectorUpdateVisibility(yearSelectId, monthSelectId, daySelectId, dateType)
{
	if (yearSelectId != null)
		$get(yearSelectId).style.display = (dateType == 2 || dateType == 3 ? '' : 'none');
	if (monthSelectId != null)
		$get(monthSelectId).style.display = (dateType == 3 ? '' : 'none');
	if (daySelectId != null)
		$get(daySelectId).style.display = (dateType == 4 ? '' : 'none');
}


// ****************************************************************
if(typeof(Sys) != 'undefined') Sys.Application.notifyScriptLoaded();
