
// Global variables
var flashContainerCount = 0;
var initDescription = "";
var textInjectForbiden = false;
var generalError = "<font color='red'>Došlo je do greške.</font>";

function OpenWindow(url, winWidth, winHeight, resizable, scrollable, winName)
{
	if (winWidth == null) winWidth = 100;
	if (winHeight == null) winHeight = 100;
	if (resizable == null) resizable = "yes";
	if (scrollable == null) scrollable = "yes";
	try
	{
		var newWindow = this.open(url, winName, "resizable=" + resizable + ", scrollbars=" + scrollable + ", status=no, width=" + winWidth + ", height=" + winHeight);
		if (newWindow) newWindow.focus();
	}
	catch(e)
	{}
}

var loading = false;
function LoadData(contentId, loadingContentId, loadUrl, loadingContentData, closureFn)
{
	var contentObj = document.getElementById(contentId);
	Show(loadingContentId);
	//if (contentObj && loading == false && lastLoadedPage != loadUrl) 
	//if (contentObj && loading == false) 
	{
		//loading = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					Hide(loadingContentId);
					ShowContent(contentObj, req.responseText);
					loading = false;
				}
    			,'onError':function(req)
				{
					Hide(loadingContentId);
					ShowContent(contentObj, req.responseText);
					loading = false;
				}
				,'onSuccess':function(req)
				{
					Hide(loadingContentId);
					ShowContent(contentObj, req.responseText);
					loading = false;
					if (closureFn) closureFn();
					if (window.SetOverCss && configuratorInitCompleted) SetOverCss();// NEDED FOR CSS CONFIGURATOR !!!!
				}
			}
		);
	}
}

function ShowContent(contentObj, contentData)
{
	try
	{
		if (contentObj)
		{
			if (contentData)
			{
				if (contentData.toString().length > 0)
				{
					if (contentObj.innerHTML.toLowerCase() != contentData.toString().toLowerCase())
					{
						contentObj.innerHTML = contentData;
					}
				}
			}
		}
	}
	catch(e)
	{}
}

function InsertDiv(targetId, htmlContent, holderId, initDisplayState, bgColorValue, classIdValue, preserve)
{
	var divObj;
	var holderObj;
	if (holderId.length > 0) holderObj = document.getElementById(holderId);
	if (targetId.length > 0)
	{
		var formatedColor;
		if (bgColorValue.length > 0) formatedColor = " bgcolor='" + bgColorValue + "'";
		var formatedClass;
		if (classIdValue.length > 0) formatedClass = " class='" + classIdValue + "'";
		var divContent = "<table width='100%' height='100%' cellspacing='0' cellpadding='0'" + formatedColor + "><tr valign='middle'><td align='center'>" + htmlContent + "</td></tr></table>";
		if (initDisplayState.length == 0) initDisplayState = "none";
		var div = "<div id='" + targetId + "' style='overflow: hidden; display: " + initDisplayState + "; position: absolute; z-Index: 100; height: 100%; width: 100%;'" + formatedClass + ">" + divContent + "</div>";
		if (holderObj)
		{
			if (preserve == true)
			{
				holderObj.innerHTML = div + holderObj.innerHTML;
				
			}
			else
			{
				holderObj.innerHTML = div;
			}
			divObj = holderObj.getElementsByTagName(targetId);
		}
		else
		{
			document.write(div);
			divObj = document.getElementById(targetId);
		}
	}
	return divObj;
}
function SubmitFormByIndex(formsIndex)
{
	if (formsIndex != null && formsIndex >= 0)
	{
		if (document.forms[formsIndex]) document.forms[formsIndex].submit();
	}
}

function InsertFlash(flashContainer, targetId)
{
	if(document.all)
	{
		if (document.all[targetId]) document.all[targetId].innerHTML = flashContainer;
	}
	else
	{
		if (document.getElementById && document.getElementById(targetId))document.getElementById(targetId).innerHTML = flashContainer;
	}
}
function FlashObjectBuilder(flashVersion, wValue, hValue, srcValue, transparent, bgColorValue, nameId, noScale, useFullscreen)
{
	if (bgColorValue == undefined) bgColorValue = "000000";
	if (transparent == undefined) transparent = true;
	if (flashVersion == undefined) flashVersion = "8";
	if (useFullscreen == undefined) useFullscreen = false;
	if (flashVersion < 9 && useFullscreen == true) flashVersion = 9;
	var revision = flashVersion + ',0,0,0';
	if (flashVersion == 9) revision = flashVersion + ',0,45,0';
	var flashCode = '<object ';
	flashCode += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
	flashCode += 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + revision + '" ';
	flashCode += 'width="' + wValue + '" ';
	flashCode += 'height="' + hValue + '" ';
	flashCode += 'id="' + nameId + '" ';
	flashCode += 'align="middle">';
	flashCode += '<param name="allowScriptAccess" value="always" />';
	flashCode += '<param name="allowNetworking" value="all" />';
	flashCode += '<param name="movie" value="' + srcValue + '" />';
	flashCode += '<param name="menu" value="false" />';
	flashCode += '<param name="quality" value="best" />';
	if (noScale == true) flashCode += '<param name="scale" value="noscale" />';
	flashCode += '<param name="salign" value="lt" />';
	if (transparent == true) flashCode += '<param name="wmode" value="transparent" />';
	if (useFullscreen == true) flashCode += '<param name="allowFullScreen" value="true" />';
	flashCode += '<param name="bgcolor" value="#' + bgColorValue + '" />';
	flashCode += '<embed ';
	flashCode += 'src="' + srcValue + '"';
	flashCode += 'menu="false" ';
	flashCode += 'quality="best" ';
	if (noScale == true) flashCode += 'scale="noscale" ';
	flashCode += 'salign="lt" ';
	if (transparent == true) flashCode += 'wmode="transparent" ';
	if (useFullscreen == true) flashCode += 'allowfullscreen="true" ';
	flashCode += 'bgcolor="#' + bgColorValue + '" ';
	flashCode += 'width="' + wValue + '" ';
	flashCode += 'height="' + hValue + '" ';
	flashCode += 'name="' + nameId + '" ';
	flashCode += 'align="middle" ';
	flashCode += 'allowScriptAccess="always" ';
	flashCode += 'allowNetworking="all" ';
	flashCode += 'type="application/x-shockwave-flash" ';
	flashCode += 'pluginspage="http://www.macromedia.com/go/getflashplayer" />';
	flashCode += '</object>';
	
	return flashCode;
}

function GetUrl(urlValue)
{
	if (urlValue.length > 0)
	{
		document.location = urlValue;
	}
}

function RestoreDiv(targetId)
{
	if (initDescription && initDescription.length > 0 && !textInjectForbiden)
	{
		if(document.all)
		{
			document.all[targetId].innerHTML = initDescription;
		}
		else
		{
			document.getElementById(targetId).innerHTML = initDescription;
		}
	}
}

function TextInDiv(textValue, targetId, ignoreInit)
{
	if (ignoreInit == null) ignoreInit = false;
	if (!textInjectForbiden)
	{
		if(document.all)
		{
			if (!ignoreInit && initDescription.length == 0) initDescription = document.all[targetId].innerHTML;
			document.all[targetId].innerHTML = textValue;
		}
		else
		{
			if (!ignoreInit && initDescription.length == 0) initDescription = document.getElementById(targetId).innerHTML;
			document.getElementById(targetId).innerHTML = textValue;
		}
	}
}

function Highlight(colorValue, targetId, isImage)
{
	var tagetObj;
	if(document.all)
	{
		tagetObj = document.all[targetId];
	}
	else
	{
		tagetObj = document.getElementById(targetId);
	}
	
	if (tagetObj)
	{
		if (isImage)
		{
			tagetObj.style.backgroundImage = "url(" + colorValue + ")";
		}
		else
		{
			tagetObj.style.background = colorValue;
		}
	}
}

function SubmitOnKey(keyCodeIndex, formTarget, e)
{
	var keynum = 0;
	if(window.event) // IE
	{
		keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which
	}
	if (formTarget && keynum == keyCodeIndex)
	{
		formTarget.submit();
	}
}

function FocusFieldOnKey(keyCodeIndex, targetField, e)
{
	var keynum = 0;
	if(window.event) // IE
	{
		keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which
	}
	
	if (targetField && keynum == keyCodeIndex)
	{
		targetField.focus();
	}
}

function FocusField(targetField)
{
	if (targetField)
	{
		targetField.focus();
	}
}

function IsVisible(elementObj)
{
	var elementVisible = false;
	if(elementObj != null && elementObj.style != null)
	{
		if(elementObj.style.display == "block" || (elementObj.style.display == "" || elementObj.style.display == undefined))
		{
			elementVisible = true;
		}
	}
	return elementVisible;
}

function IsVisibleById(elementId)
{
	var elementVisible = false;
	var elementObj = GetObjById(elementId);
	if(elementObj != null && elementObj.style != null)
	{
		if(elementObj.style.display == "block" || (elementObj.style.display == "" || elementObj.style.display == undefined))
		{
			elementVisible = true;
		}
	}
	return elementVisible;
}
function ShowHide(elementId)
{
	var srcElement = GetObjById(elementId);
	if(srcElement != null && srcElement.style != null)
	{
		if(srcElement.style.display == "block" || (srcElement.style.display == "" || srcElement.style.display == undefined))
		{
			srcElement.style.display= 'none';
		}
		else
		{
			srcElement.style.display='block';
		}
	}
	return false;
}




function Hide(elementId)
{
	if(elementId != null)
	{
		var srcElement = GetObjById(elementId);
		if(srcElement != null)
		{
			srcElement.style.display= 'none';
		}
	}
	return false;
}

function Show(elementId)
{
	if (elementId != null)
	{
		var srcElement = GetObjById(elementId);
		if(srcElement != null)
		{
			if(srcElement.style.display == "" || srcElement.style.display == null || srcElement.style.display == "none")
			{
				srcElement.style.display= 'block';
			}
		}
	}
	return false;
}

function DisableSelect(target)
{
	if (typeof target.onselectstart != "undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}
	//target.style.cursor = "default"
}

function ChangeCss(obj, borderColorLeft, borderColorTop, borderColorRight, borderColorBottom, borderSize)
{
	if (!borderSize || borderSize.length == 0 || borderSize <= 0) borderSize = 1;
	if (obj && borderColorLeft && borderColorLeft.length > 0)
	{
		if ((!borderColorTop || borderColorTop.length == 0) && (!borderColorRight || borderColorRight.length == 0) && (!borderColorBottom || borderColorBottom.length == 0))
		{
			obj.style.borderColor = "#" + borderColorLeft;
		}
		else
		{
			obj.style.borderLeft = borderSize + "px #" + borderColorLeft + " solid";
			obj.style.borderTop = borderSize + "px #" + borderColorTop + " solid";
			obj.style.borderRight = borderSize + "px #" + borderColorRight + " solid";
			obj.style.borderBottom = borderSize + "px #" + borderColorBottom + " solid";
		}
	}
}

function BookmarkData()
{
	if (window.sidebar)
	{
		// firefox
		window.sidebar.addPanel(document.title, location.href, "");
	}
	else if (document.all && !window.opera)
	{
		// IE
		window.external.AddFavorite(location.href, document.title);
	}
	else if (window.opera && window.print)
	{
		// opera
		//var elem = document.createElement('a');
		//elem.setAttribute('href', location.href);
		//elem.setAttribute('title', document.title);
		//elem.setAttribute('rel', 'sidebar');
		//elem.click();
		alert("Pritisnite Ctrl-D");
	}
}

function CheckCharCount(maxChars, fieldObj, labelId)
{
	if (fieldObj && maxChars > 0)
	{
		var label = document.getElementById(labelId);
		var currentLength = fieldObj.value.length;
		if (currentLength >= maxChars - 1)
		{
			fieldObj.value = String(fieldObj.value).substring(0, maxChars);
		}
		var remaining = maxChars - currentLength;
		if (remaining < 0) remaining = 0;
		if (remaining > maxChars) remaining = maxChars;
		label.innerHTML = remaining;
	}
}

function SubmitForm(formId)
{
	if (formId && formId.length > 0)
	{
		var objForm = document.getElementById(formId);
		if (objForm != undefined)
		{
			objForm.submit();
		}
	}
}

function GetObjById(targetId)
{
	var targetObj;
	if (targetId && targetId.length > 0)
	{
		if (document.getElementById && document.getElementById(targetId)) targetObj = document.getElementById(targetId);
	}
	return targetObj;
}


function InsertText(targetId, textToInsert)
{
	if (textToInsert)
	{
		var targetObj = GetObjById(targetId);
		if (targetObj)
		{
			targetObj.innerHTML = textToInsert;
		}
	}
}
function GetFlashMovieObject(movieName)
{
	if (window.document[movieName]) 
	{
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1)
	{
		if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName]; 
	}
	else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
	{
		return document.getElementById(movieName);
	} 
}
function AddLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
		    	oldonload();
		    }
		    func();
		}
	}
}

// For submiting login form
function SubmitLogin(usernameId, passwordId)
{
	var objUsername = window[usernameId];
	var objPassword = window[passwordId];
	if (objUsername && objPassword)
	{
		var username = objUsername.GetValue();
		var password = objPassword.GetValue();
		if (username.length > 0 && password.length > 0)
		{
			var localLoginForm = document.frmLocalLogin;
			if (localLoginForm)
			{
				// Local login
				localLoginForm.rtbUsername.value = username;
				localLoginForm.rtbPassword.value = password;
				localLoginForm.submit();
			}
			else
			{
				// SSO
				var ssoLoginForm = document.frmSsoLogin;
				if (ssoLoginForm)
				{
					ssoLoginForm.username.value = username;
					ssoLoginForm.password.value = password;
					ssoLoginForm.submit();
				}
			}
		}
		else
		{
			// Show error
			var objInfo = document.getElementById("boxLoginTabInfo");
			if (objInfo)
			{
				Show("holderLoginTabInfo");
				objInfo.innerHTML = "Unesite korisničko ime i lozinku";
			}
		}
	}
}

function GetRadioValue(fieldName, formObj)
{
	var fieldValue = "";
	if (fieldName && fieldName.length > 0 && formObj)
	{
		for(var i = 0;i < formObj[fieldName].length;i++)
		{
			if (formObj[fieldName][i].checked == true)
			{
				fieldValue = formObj[fieldName][i].value;
			}
		}
	}
	return fieldValue;
}

function GetFieldValue(fieldId, fieldType, formObj)
{
	var fieldValue = "";
	if(fieldId && fieldId.length > 0)
	{
		var fieldObj = GetObjById(fieldId);
		if (fieldObj)
		{
			switch(fieldType)
			{
				case 1: // text
					if (fieldObj) fieldValue = fieldObj.value;
					break;
					
				case 2: // password
					if (fieldObj) fieldValue = fieldObj.value;
					break;
					
				case 3: // radio
					if (formObj) fieldValue = GetRadioValue(fieldId, formObj);
					break;
					
				case 4: // select
					if (fieldObj) fieldValue = fieldObj.value;
					break;
					
				default:
					break;
			}
		}
	}
	return fieldValue;
}

function SubmitBasicRegistration(netId, email, password, firstname, repeatPassword, lastName, gender, yob, validationCode)
{
	var mandatoryCheckPassed = false;
	var objInfo = document.getElementById("boxRegistrationInfo");
	
	var netIdValue = GetFieldValue(netId, 1);
	var emailValue = GetFieldValue(email, 1);
	var passwordValue = GetFieldValue(password, 2);
	var firstnameValue = GetFieldValue(firstname, 2);
	var repeatPasswordValue = GetFieldValue(repeatPassword, 2);
	var lastNameValue = GetFieldValue(lastName, 2);
	var genderValue = GetFieldValue(gender, 3, document.forms[0]);
	var yobValue = GetFieldValue(yob, 4);
	var validationCodeValue = GetFieldValue(validationCode, 1);
	
	var netIdOuterC = netId + "_OuterC";
	var netIdInnerC = netId + "_InnerC";
	var emailOuterC = email + "_OuterC";
	var emailInnerC = email + "_InnerC";
	var passwordOuterC = password + "_OuterC";
	var passwordInnerC = password + "_InnerC";
	var repeatPasswordOuterC = repeatPassword + "_OuterC";
	var repeatPasswordInnerC = repeatPassword + "_InnerC";
	var validationCodeOuterC = validationCode + "_OuterC";
	var validationCodeInnerC = validationCode + "_InnerC";
							
	// Reset fields layout
	ChangeBorder(netIdOuterC, "d3d2d0", "d3d2d0", "d3d2d0", "d3d2d0");
	ChangeBorder(netIdInnerC, "40403e", "40403e", "ffffff", "ffffff");
	ChangeBorder(emailOuterC, "d3d2d0", "d3d2d0", "d3d2d0", "d3d2d0");
	ChangeBorder(emailInnerC, "40403e", "40403e", "ffffff", "ffffff");
	ChangeBorder(passwordOuterC, "d3d2d0", "d3d2d0", "d3d2d0", "d3d2d0");
	ChangeBorder(passwordInnerC, "40403e", "40403e", "ffffff", "ffffff");
	ChangeBorder(repeatPasswordOuterC, "d3d2d0", "d3d2d0", "d3d2d0", "d3d2d0");
	ChangeBorder(repeatPasswordInnerC, "40403e", "40403e", "ffffff", "ffffff");
	ChangeBorder(validationCodeOuterC, "d3d2d0", "d3d2d0", "d3d2d0", "d3d2d0");
	ChangeBorder(validationCodeInnerC, "40403e", "40403e", "ffffff", "ffffff");
	
	var netIdMinChars = 5;
	var passwordMinChars = 6;
	var emailMinChars = 6;
	var validationCodeMinChars = 5;
	if (netIdValue && netIdValue.length >= netIdMinChars && ValidFieldChars(netIdValue) && emailValue && emailValue.length >= emailMinChars && IsEmail(emailValue) && passwordValue && passwordValue.length >= passwordMinChars && repeatPasswordValue && repeatPasswordValue.length >= passwordMinChars && repeatPasswordValue == passwordValue && validationCodeValue && validationCodeValue.length == validationCodeMinChars)
	{
		// Check if validation code is valid
		var loadUrl = "_ajaxCalls/checkValidationCode.aspx?userCode=" + validationCodeValue;
		if (loading == false) 
		{
			loading = true;
			AjaxRequest.get
			(
				{
					'url': loadUrl
					,'timeout':20000
					,'onLoading':function(req)
					{
					}
   					,'onTimeout':function(req)
					{
						loading = false;
						// validation code invalid, Show error
						Show("holderRegistrationInfo");
						objInfo.innerHTML = "Došlo je do greške prilikom validiranja upisanog koda.";
						ChangeBorder(validationCodeOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
						ChangeBorder(validationCodeInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
					}
    				,'onError':function(req)
					{
						loading = false;
						// validation code invalid, Show error
						Show("holderRegistrationInfo");
						objInfo.innerHTML = "Došlo je do greške prilikom validiranja upisanog koda.";
						ChangeBorder(validationCodeOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
						ChangeBorder(validationCodeInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
					}
					,'onSuccess':function(req)
					{
						loading = false;
						if (req.responseText == "status=ok&error=0")
						{
							// validation code valid
							// Submit form
							SubmitUserRegistration(netIdValue, emailValue, passwordValue, firstnameValue, repeatPasswordValue, lastNameValue, genderValue, yobValue, validationCodeValue);	
						}
						else
						{
							// validation code invalid, Show error
							Show("holderRegistrationInfo");
							objInfo.innerHTML = "Kod koji ste upisali ne odgovara kodu na slici.";
							ChangeBorder(validationCodeOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
							ChangeBorder(validationCodeInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
						}
					}
				}
			);
		}
		loading = false;
	}
	else
	{
		// Show error
		mandatoryCheckPassed = false;
		
		// Show error
		if (objInfo)
		{
			Show("holderRegistrationInfo");
			var errorText = "";
			var errCount = 0;
			if (netIdValue == null || netIdValue.length < netIdMinChars || !ValidFieldChars(netIdValue))
			{
				// No netId
				errCount++;
				errorText = "netID korisničko ime sadrži premalo znakova, nemojte koristiti dijakritičke znakove.";
				if (!ValidFieldChars(netIdValue)) errorText = "netID korisničko ime sadrži nedozvoljene znakove, dozvoljni su samo brojevi i slova bez dijakritičkih znakova i razmaka.";
				ChangeBorder(netIdOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(netIdInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			if (emailValue == null || emailValue.length < emailMinChars || !IsEmail(emailValue))
			{
				// No email
				errCount++;
				errorText = "Niste dobro formatirali email adresu.";
				ChangeBorder(emailOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(emailInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			if (passwordValue == null || passwordValue.length  < passwordMinChars)
			{
				// No password
				errCount++;
				errorText = "Lozinka nije upisana ili sadrži premalo znakova.";
				ChangeBorder(passwordOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(passwordInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			if (repeatPasswordValue == null || repeatPasswordValue.length < passwordMinChars)
			{
				// No repeatPassword
				errCount++;
				errorText = "Ponovljena lozinka nije upisana ili sadrži premalo znakova.";
				ChangeBorder(repeatPasswordOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(repeatPasswordInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			if (errCount > 1) errorText = "Sva polja označena * moraju biti ispunjena. Pazite na minimalni broj znakova."
			if (passwordValue && passwordValue.length > 0 && repeatPasswordValue && repeatPasswordValue.length > 0 && passwordValue != repeatPasswordValue)
			{
				// Password and repeat password are not the same
				errCount++;
				if (errorText && errorText.length > 0) errorText += "<br>";
				errorText += "Lozinka i ponovljena lozinka nisu iste, pazite na minimalni broj znakova.";
				ChangeBorder(passwordOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(passwordInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
				ChangeBorder(repeatPasswordOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(repeatPasswordInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			if (validationCodeValue == null || validationCodeValue.length != validationCodeMinChars)
			{
				// No validationCode
				if (errorText && errorText.length > 0) errorText += "<br>";
				errorText += "Niste upisali kod prikazan na slici ili ste upisal kod koji sadrži premalo znakova.";
				ChangeBorder(validationCodeOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(validationCodeInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			objInfo.innerHTML = errorText;
		}
	}
}

function SubmitUserRegistration(netIdValue, emailValue, passwordValue, firstnameValue, repeatPasswordValue, lastNameValue, genderValue, yobValue, validationCodeValue)
{
	//submit
	if (genderValue && genderValue == 1)
	{
		genderValue = "M";
	}
	else
	{
		genderValue = "F";
	}
	//YYYY-MM-DD
	if (yobValue && yobValue > 0)
	{
	
		yobValue = yobValue + "-01-01";
	}
	else
	{
		yobValue = "";
	}
	var loadUrl = "https://komunikator.tportal.hr/NetID/clientreg.nhtm?output=js&netid=" + escape(netIdValue) + "&password=" + escape(passwordValue) + "&email=" + escape(emailValue) + "&firstname=" + escape(firstnameValue) + "&lastname=" + escape(lastNameValue) + "&gender=" + escape(genderValue) + "&birthday=" + escape(yobValue);
	//var loadUrl = "https://komunikator.tportal.hr/NetID/clientreg.nhtm?output=js";
	document.getElementById('netid').src = loadUrl;
}

// Used for net id
function netid_data(obj)
{
	if (obj)
	{
		obj.loginStatus;
		obj.message;
		obj.properties;
		obj.status;
		if (obj.status > 0)
		{
			// User created, show info
			Hide("registrationContent");
			Show("registeredContent");
			if (obj.message != null && obj.message.length > 3)
			{
				var objInfo = document.getElementById("boxRegisteredInfo");
				if (objInfo) objInfo.innerHTML = obj.message;
			}
		}
		else
		{
			// Show errors
			Show("holderRegistrationInfo");
			var objInfo = document.getElementById("boxRegistrationInfo");
			if (objInfo) objInfo.innerHTML = obj.message;
		}
	}
}

function IsEmail(mail)
{
	var isValid = false;
	if (mail && mail.length > 5)
	{
		var emailReg = "^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$";
		var regex = new RegExp(emailReg, "i");
		isValid = regex.test(mail);
	}
	return isValid;
}

// Validates characters, no čćžšđ or special chars, used in username creation
function ValidFieldChars(fieldValue)
{
	var isValid = true;
	if (fieldValue && fieldValue.length > 0)
	{
		var regex = new RegExp("[^0-9a-z]", "i");
		isValid = !regex.test(fieldValue);
	}
	return isValid;
}

// For submiting login form
function SubmitBasicLogin(usernameId, passwordId, rememberMeId, currentUrl)
{
	var username = document.forms[0][usernameId].value;
	var password = document.forms[0][passwordId].value;
	
	var rememberMe = document.forms[0][rememberMeId].checked;
	if (rememberMe) rememberMe = 1;
	else rememberMe = 0;
	
	var usernameOuterC = usernameId + "_OuterC";
	var usernameInnerC = usernameId + "_InnerC";
	var passwordOuterC = passwordId + "_OuterC";
	var passwordInnerC = passwordId + "_InnerC";
		
	if (username != null && username.length > 0 && password != null && password.length > 0)
	{
		
		// Reset fields layout
		ChangeBorder(usernameOuterC, "d3d2d0", "d3d2d0", "d3d2d0", "d3d2d0");
		ChangeBorder(usernameInnerC, "40403e", "40403e", "ffffff", "ffffff");
		ChangeBorder(passwordOuterC, "d3d2d0", "d3d2d0", "d3d2d0", "d3d2d0");
		ChangeBorder(passwordInnerC, "40403e", "40403e", "ffffff", "ffffff");
		
		var localLoginForm = document.frmLocalLogin;
		if (localLoginForm)
		{
			// Local login
			localLoginForm.rtbUsername.value = username;
			localLoginForm.rtbPassword.value = password;
			localLoginForm.chkRememberMe.value = rememberMe;
			localLoginForm.currentUrl.value = currentUrl;
			localLoginForm.submit();
		}
		else
		{
			// SSO
			var ssoLoginForm = document.frmSsoLogin;
			if (ssoLoginForm)
			{
				ssoLoginForm.username.value = username;
				ssoLoginForm.password.value = password;
				ssoLoginForm.chkRememberMe.value = rememberMe;
				ssoLoginForm.currentUrl.value = currentUrl;
				ssoLoginForm.submit();
			}
		}
	}
	else
	{
		// Show error
		var objInfo = document.getElementById("boxLoginTabInfo");
		if (objInfo)
		{
			var errorText = "";
			var errorCount = 0;
			Show("holderLoginTabInfo");
			if (username == null || username.length <= 0)
			{
				errorCount++;
				errorText = "Unesite korisničko ime";
				ChangeBorder(usernameOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(usernameInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			if (password == null || password.length <= 0)
			{
				errorCount++;
				errorText = "Unesite lozinku";
				ChangeBorder(passwordOuterC, "9c0410", "9c0410", "9c0410", "9c0410");
				ChangeBorder(passwordInnerC, "ffffff", "ffffff", "ffffff", "ffffff");
			}
			if (errorCount > 1) errorText = "Unesite korisničko ime i lozinku";
			objInfo.innerHTML = errorText;
		}
	}
}

// send to friend
var sendingToFriend = false;
function SendToFriend(uniqueId, fromId, toId, messageId, videoId, videoTitle)
{
	if (fromId.length > 0 && toId.length > 0 && messageId.length > 0 && videoId > 0 && videoTitle.length > 0)
	{
		// Locate form and set values
		var targetForm = document.frmSendToFriend;
		var objSendToFriendStatus = document.getElementById("sendToFriendStatus");
		if (targetForm)
		{
			// Refrencing target form
			var objSendFrom = targetForm.rtbFrom;
			var objSendTo = targetForm.rtbTo;
			var objSendMessage = targetForm.rtbMessage;
			var objSendId = targetForm.videoId;
			var objSendTitle = targetForm.videoTitle;
			
			if (objSendFrom && objSendTo && objSendMessage && objSendId && objSendTitle)
			{
				// Refrencing source fields
				var objFrom = window[fromId];
				var objTo = window[toId];
				var objMessage = window[messageId];
				
				if (objFrom && objTo && objMessage)
				{
					// Setting values
					objSendFrom.value = objFrom.GetValue();
					objSendTo.value = objTo.GetValue();
					objSendMessage.value = objMessage.GetValue();
					objSendId.value = videoId;
					objSendTitle.value = videoTitle;
					
					// Values set, submiting
					if (AjaxRequest && !sendingToFriend)
					{
						var oldButtonValue = "";
						var objButton = document.getElementById("sendToFriendBtn_" + uniqueId);
						if (objButton)
						{
							oldButtonValue = objButton.innerHTML;
							objButton.innerHTML = "<img src='img/loading.gif' alt=''>";
						}
						sendingToFriend = true;
						status = AjaxRequest.submit
						(
							targetForm,
							{
								'onError':function(req)
								{
									// Error handling
									//alert(req.responseText)
									sendingToFriend = false;
									if (objSendToFriendStatus) objSendToFriendStatus.innerHTML = generalError;
								}
								,'onTimeout':function(req)
								{
									// Error handling
									sendingToFriend = false;
									if (objSendToFriendStatus) objSendToFriendStatus.innerHTML = generalError;
								}
								,'onSuccess':function(req)
								{
									sendingToFriend = false;
									if (req.responseText == "status=saved&error=0")
									{
										// Saved, reload comment list
										if (objSendToFriendStatus) objSendToFriendStatus.innerHTML = "Poruka je poslana";
									}
									else if (req.responseText == "status=badMail&error=1")
									{
										// Error handling
										if (objSendToFriendStatus) objSendToFriendStatus.innerHTML = "<font color='red'>Upisana email adresa nije dobro formatirana</font>";
									}
									else if (req.responseText == "status=noData&error=1")
									{
										// Error handling
										if (objSendToFriendStatus) objSendToFriendStatus.innerHTML = "<font color='red'>Morate upisati email adresu pošiljaoca i primatelja</font>";
									}
									else
									{
										// Error handling
										if (objSendToFriendStatus) objSendToFriendStatus.innerHTML = generalError;
									}
								}
							}
						);
						sendingToFriend = false;
						targetForm.reset();
						if (objTo) objTo.Clear();
						if (objMessage) objMessage.Clear();
						if (objButton && oldButtonValue.length > 0) objButton.innerHTML = oldButtonValue;
					}
				}
			} 
		}
	}
	else
	{
		// Error handling
		sendingToFriend = false;
		if (objSendToFriendStatus) objSendToFriendStatus.innerHTML = generalError;
	}
}

// simple term only search
function SubmitSimpleSearch(searchTermId)
{
	var objSearchTerm = window[searchTermId];
	if (objSearchTerm)
	{
		var searchTerm = objSearchTerm.GetValue();
		if (searchTerm.length > 0)
		{
			document.frmSearch.rtbSearchTerm.value = searchTerm;
			document.frmSearch.submit();
		}
		else
		{
			// Show error
			alert("Morate ispuniti polje Traži");
			//objSearchTerm.EmptyMessage.value = "Morate ispuniti polje Traži";
		}
	}
}
// advanced search
function SubmitAdvancedSearch(searchTermId, searchTypeName, searchCategoryId, searchGradeRangeId, searchDurationRangeId, searchVideoCountId, searchPublishedRangeId, searchInTableName)
{
	var objSearchTerm = window[searchTermId];
	if (objSearchTerm)
	{
		var searchTerm = objSearchTerm.GetValue();
		if (searchTerm.length > 0)
		{
			document.frmAdvancedSearch.rtbSearchTerm.value = searchTerm;
			
			var searchType = GetCheckedValue(document.forms[0][searchTypeName]);
			if (searchType.length > 0) document.frmAdvancedSearch.rbSearchType.value = searchType;
			
			var searchInTable = GetCheckedValue(document.forms[0][searchInTableName]);
			if (searchInTable.length > 0) document.frmAdvancedSearch.rbSearchInTable.value = searchInTable;		
			
			var objSearchCategory = window[searchCategoryId];
			if (objSearchCategory)
			{
				var searchCategory = objSearchCategory.GetValue();
				if (searchCategory.length > 0) document.frmAdvancedSearch.rcbSearchCategory.value = searchCategory;
			}
			
			var objSearchGradeRange = window[searchGradeRangeId];
			if (objSearchGradeRange)
			{
				var searchGradeRange = objSearchGradeRange.GetValue();
				if (searchGradeRange.length > 0) document.frmAdvancedSearch.rcbSearchGradeRange.value = searchGradeRange;
			}
			
			var objSearchDurationRange = window[searchDurationRangeId];
			if (objSearchDurationRange)
			{
				var searchDurationRange = objSearchDurationRange.GetValue();
				if (searchDurationRange.length > 0) document.frmAdvancedSearch.rcbSearchDurationRange.value = searchDurationRange;
			}
			
			var objSearchVideoCount = window[searchVideoCountId];
			if (objSearchVideoCount)
			{
				var searchVideoCount = objSearchVideoCount.GetValue();
				if (searchVideoCount.length > 0) document.frmAdvancedSearch.rcbSearchVideoCount.value = searchVideoCount;
			}
			
			var objSearchPublishedRange = window[searchPublishedRangeId];
			if (objSearchPublishedRange)
			{
				var searchPublishedRange = objSearchPublishedRange.GetValue();
				if (searchPublishedRange.length > 0) document.frmAdvancedSearch.rcbSearchPublishedRange.value = searchPublishedRange;
			}
			
			document.frmAdvancedSearch.submit();
		}
		else
		{
			// Show error
			alert("Morate ispuniti polje Traži");
			//objSearchTerm.EmptyMessage.value = "Morate ispuniti polje Traži";
		}
	}
}
function GetCheckedValue(radioObj) 
{
	var selectedValue = "";
	if (radioObj)
	{
		var radioLength = radioObj.length;
		if(radioLength == undefined)
		{
			if(radioObj.checked)
			{
				selectedValue = radioObj.value;
			}
		}
		
		for(var i = 0; i < radioLength; i++) 
		{
			if(radioObj[i].checked)
			{
				selectedValue = radioObj[i].value;
			}
		}
	}
	return selectedValue;
}

// Submiting lost password form
function SubmitLostPassword(email)
{
	var objEmail = window[email];
	if (objEmail)
	{
		var mail = objEmail.GetValue();
		if (mail.length > 0)
		{
			document.frmLostPassword.rtbLostPasswordEmail.value = mail;
			document.frmLostPassword.submit();
		}
		else
		{
			// Show error
			var objInfo = document.getElementById("boxLoginTabMailError");
			if (objInfo)
			{
				Show("holderLoginTabMailInfo");
				objInfo.innerHTML = "Unesite email adresu koju ste ostavili prilikom registracije";
			}
		}
	}
}

function MessageRead(userMessageId, index)
{
	if (userMessageId > 0 && loading == false) 
	{
		var loadUrl = "_ajaxCalls/SetMessageRead.aspx?userMessageId=" + userMessageId;
		if (loading == false) 
		{
			loading = true;
			AjaxRequest.get
			(
				{
					'url': loadUrl
					,'timeout':20000
					,'onLoading':function(req)
					{
					}
   					,'onTimeout':function(req)
					{
						loading = false;
					}
    				,'onError':function(req)
					{
						loading = false;
					}
					,'onSuccess':function(req)
					{
						loading = false;
						if (req.responseText == "status=set&error=0" || req.responseText == "status=allreadySet&error=0")
						{
							// Save done
							var objMsgFrom = document.getElementById("msgFrom_" + index);
							var objMsgSubject = document.getElementById("msgSubject_" + index);
							var objMsgDate = document.getElementById("msgDate_" + index);
							
							if (objMsgFrom != null) objMsgFrom.style.fontWeight = "normal";
							if (objMsgSubject != null) objMsgSubject.style.fontWeight = "normal";
							if (objMsgDate != null) objMsgDate.style.fontWeight = "normal";
						}
					}
				}
			);
		}
	}
	loading = false;
}
/*
=================================
Currently used status report list
=================================
ERRORS:  saveError, notLoggedIn, noVideoId
SUCCESS: added
=================================
FLAGS: status=&error=(0,1)
=================================
*/
function AddToFavorite(iconContainer, videoId)
{
	if (videoId > 0 && loading == false) 
	{
		var loadUrl = "_ajaxCalls/AddToPlaylist.aspx?videoId=" + videoId;
		if (loading == false) 
		{
			loading = true;
			AjaxRequest.get
			(
				{
					'url': loadUrl
					,'timeout':20000
					,'onLoading':function(req)
					{
					}
   					,'onTimeout':function(req)
					{
						loading = false;
					}
    				,'onError':function(req)
					{
						loading = false;
					}
					,'onSuccess':function(req)
					{
						loading = false;
						if (req.responseText == "status=added&error=0" || req.responseText == "status=allreadyAdded&error=0")
						{
							// Save done
							// Hide icon
							if (iconContainer && iconContainer.style) iconContainer.style.display = 'none';
							if (window.ReloadPlaylist) ReloadPlaylist();
							if (window.ReloadPlaylistRelatedData) ReloadPlaylistRelatedData();
							
							/*
							// Show and hide items
							var playlistDisplay = document.getElementById("PlaylistHolder").style.display;
							if (playlistDisplay == "none") Show("PlaylistHolder");
							Hide("PlaylistInfo");
							
							// Reload flash
							if (playlistDisplay != "none")
							{
								ReloadPlaylist();
							}
							else
							{
								// Reload only for not IE browsers, IE will reload automatically
								if (navigator.appName.indexOf("Microsoft Internet")==-1) ReloadPlaylist();
							}
							*/
						}
					}
				}
			);
		}
	}
	loading = false;
}
function RemoveFav(iconContainer, videoId)
{
	if (loading == false) 
	{
		var loadUrl = "_ajaxCalls/AddToPlaylist.aspx?videoId=" + videoId + "&remove=true";
		if (loading == false) 
		{
			loading = true;
			AjaxRequest.get
			(
				{
					'url': loadUrl
					,'timeout':20000
					,'onLoading':function(req)
					{
					}
   					,'onTimeout':function(req)
					{
						loading = false;
					}
    				,'onError':function(req)
					{
						loading = false;
					}
					,'onSuccess':function(req)
					{
						loading = false;
						if (req.responseText == "status=deleted&error=0")
						{
							// Save done
							// Hide icon
							if (iconContainer) iconContainer.style.display = 'none';
							if (window.ReloadPlaylist) ReloadPlaylist();
							if (window.ReloadPlaylistRelatedData) ReloadPlaylistRelatedData();
							
							/*
							// Show and hide items
							var playlistDisplay = document.getElementById("PlaylistHolder").style.display;
							if (playlistDisplay == "none") Show("PlaylistHolder");
							Hide("PlaylistInfo");
							
							// Reload flash
							if (playlistDisplay != "none")
							{
								ReloadPlaylist();
							}
							else
							{
								// Reload only for not IE browsers, IE will reload automatically
								if (navigator.appName.indexOf("Microsoft Internet")==-1) ReloadPlaylist();
							}
							*/
						}
					}
				}
			);
		}
	}
	loading = false;
}

/*
function ReloadPlaylist()
{
	var movieObj = GetFlashMovieObject("PlaylistDisplay");
	if (movieObj) movieObj.Reload();
}
*/

function GetFlashMovieObject(movieName)
{
	if (window.document[movieName]) 
	{
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1)
	{
		if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName]; 
	}
	else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
	{
		return document.getElementById(movieName);
	}
}

// Ajax Calls
	var uniqueIdTabVideos, holderIdTabVideos, loadingIdTabVideos, mainIndexTabVideos, subIndexTabVideos, channelIdTabVideos, pageTabVideos, layoutTabVideos, showCategoryTabVideos, videosPerRowTabVideos, rowsTabVideos, recordcountTabVideos, userChoiceVisibilityTabVideos, includePrivateChannels;
function LoadTabVideos(uniqueId, holderId, loadingId, mainIndex, subIndex, channelId, page, layout, showCategory, videosPerRow, rows, recordcount, userChoiceVisibility, showAll, showAllData, includePrivate)
{
	uniqueIdTabVideos = uniqueId;
	holderIdTabVideos = holderId;
	loadingIdTabVideos = loadingId;
	mainIndexTabVideos = mainIndex;
	subIndexTabVideos = subIndex;
	channelIdTabVideos = channelId;
	pageTabVideos = page;
	layoutTabVideos = layout;
	showCategoryTabVideos = showCategory;
	videosPerRowTabVideos = videosPerRow;
	rowsTabVideos = rows;
	recordcountTabVideos = recordcount;
	userChoiceVisibilityTabVideos = userChoiceVisibility;
	includePrivateChannels = includePrivate;
	
	LoadData(holderId, loadingId, "_ajaxCallsTabVideosHolder.aspx?mainIndex=" + mainIndex + "&subIndex=" + subIndex + "&channelId=" + channelId + "&page=" + page + "&layout=" + layout + "&showCategory=" + showCategory + "&videosPerRow=" + videosPerRow + "&rows=" + rows + "&recordcount=" + recordcount + "&holderUniqueId=" + uniqueId + "&userChoiceVisibility=" + userChoiceVisibility + "&showAll=" + showAll + "&showAllData=" + showAllData + "&includePrivateChannels=" + includePrivate);
}

function LoadAddToFav(uniqueId, holderId, videoId)
{
	LoadData(holderId, "", "_ajaxCallsAddToFavContainer.aspx?videoId=" + videoId + "&holderUniqueId=" + uniqueId);
}
function LoadChoiceGrid(uniqueId, holderId, loadingId, tabIndex)
{
	LoadData(holderId, loadingId, "_ajaxCallsChoiceGrid.aspx?tabIndex=" + tabIndex + "&holderUniqueId=" + uniqueId);
}

function LoadPlaylist(uniqueId, holderId, loadingId, showCategory, showComments, showViews, layout, autoplay, videoId, layoutWidth)
{
	LoadData(holderId, loadingId, "_ajaxCallsPlaylist.aspx?showCategory=" + showCategory + "&showComments=" + showComments + "&showViews=" + showViews + "&layout=" + layout + "&holderUniqueId=" + uniqueId + "&autoplay=" + autoplay + "&videoId=" + videoId + "&layoutWidth=" + layoutWidth);
}
function LoadArchive(uniqueId, holderId, loadingId, showCategory, showComments, showViews, layout, videoId, channelId, maxVideoCount)
{
	LoadData(holderId, loadingId, "_ajaxCallsArchive.aspx?showCategory=" + showCategory + "&showComments=" + showComments + "&showViews=" + showViews + "&layout=" + layout + "&holderUniqueId=" + uniqueId + "&videoId=" + videoId + "&channelId=" + channelId + "&maxVideoCount=" + maxVideoCount);
}
function LoadRelatedVideos(uniqueId, holderId, loadingId, showCategory, showComments, showViews, layout, videoId, channelId, maxVideoCount)
{
	LoadData(holderId, loadingId, "_ajaxCallsRelatedVideos.aspx?showCategory=" + showCategory + "&showComments=" + showComments + "&showViews=" + showViews + "&layout=" + layout + "&holderUniqueId=" + uniqueId + "&videoId=" + videoId + "&channelId=" + channelId + "&maxVideoCount=" + maxVideoCount);
}
function LoadWatchedVideos(uniqueId, holderId, loadingId, showCategory, showComments, showViews, layout, videoId, channelId, maxVideoCount, layoutWidth)
{
	LoadData(holderId, loadingId, "_ajaxCallsWatchedVideos.aspx?showCategory=" + showCategory + "&showComments=" + showComments + "&showViews=" + showViews + "&layout=" + layout + "&holderUniqueId=" + uniqueId + "&videoId=" + videoId + "&channelId=" + channelId + "&maxVideoCount=" + maxVideoCount + "&layoutWidth=" + layoutWidth);
}
function LoadUcFriends(uniqueId, holderId, loadingId, channelId, page)
{
	LoadData(holderId, loadingId, "_ajaxCallsUcFriends.aspx?holderUniqueId=" + uniqueId + "&channelId=" + channelId + "&friendsUcPage=" + page);
}
function LoadUcSubscriptions(uniqueId, holderId, loadingId, channelId, ownerId, page)
{
	LoadData(holderId, loadingId, "_ajaxCallsUcSubscriptions.aspx?holderUniqueId=" + uniqueId + "&channelId=" + channelId + "&ownerId=" + ownerId + "&friendsUcPage=" + page);
}
function LoadUcPollBox(uniqueId, holderId, loadingId, channelId, ownerId, page, pollOption, showResults)
{
	LoadData(holderId, loadingId, "_ajaxCallsUcPollBox.aspx?holderUniqueId=" + uniqueId + "&channelId=" + channelId + "&ownerId=" + ownerId + "&pollBoxUcPage=" + page + "&pollOption=" + pollOption + "&showResults=" + showResults);
}
function LoadComments(uniqueId, holderId, loadingId, mainIndex, channelId, videoId, page, commentListSizeType, rows, showTitle, enableReply)
{
	LoadData(holderId, loadingId, "_ajaxCallsTabCommentsHolder.aspx?mainIndex=" + mainIndex + "&channelId=" + channelId + "&videoId=" + videoId + "&page=" + page + "&holderUniqueId=" + uniqueId + "&commentListSizeType=" + commentListSizeType + "&rows=" + rows + "&showTitle=" + showTitle + "&enableReply=" + enableReply);
}

var gradingComment = false;
function GradeCurrentComment(itemIndex, commentId, gradeLevel, channelId, videoId, currentGrade)
{
	// gradeLevel is used to set positive or negative comment grade
	var loadUrl = "_ajaxCalls/GradeComment.aspx?commentId=" + commentId + "&channelId=" + channelId + "&videoId=" + videoId + "&gradeLevel=" + gradeLevel;
	if (gradingComment == false) 
	{
		gradingComment = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					gradingComment = false;
				}
    			,'onError':function(req)
				{
					gradingComment = false;
				}
				,'onSuccess':function(req)
				{
					gradingComment = false;
					if (req.responseText == "status=graded&error=0")
					{
						var thumbsUp = document.getElementById("comment_thumbsUp_" + itemIndex);
						var thumbsDown = document.getElementById("comment_thumbsDown_" + itemIndex);
						var commentRating = document.getElementById("comment_rating_" + itemIndex);
						if (thumbsUp && thumbsDown && commentRating)
						{
							// Handle grade display
							if (currentGrade == NaN) currentGrade = 0;
							
							var grade = parseInt(gradeLevel);
							if (grade < 0) grade = -1;
							if (grade > 0) grade = 1;
							
							currentGrade = currentGrade + grade;
							var showRating = currentGrade.toString();
							if (currentGrade < 0) showRating = "<font color='#ff6633'>" + currentGrade + "</font>";
							
							commentRating.innerHTML = showRating;
							
							// Handle javascript actions and image titles, alt
							thumbsUp.onMouseOver = "return false";
							thumbsUp.onMouseOut = "return false";
							thumbsUp.onmousedown = "return false";
							thumbsUp.onclick = "";
							thumbsUp.title = "Već ste ocjenili";
							thumbsUp.alt = "Već ste ocjenili";
							
							thumbsDown.onMouseOver = "return false";
							thumbsDown.onMouseOut = "return false";
							thumbsDown.onmousedown = "return false";
							thumbsDown.onclick = "";
							thumbsDown.title = "Već ste ocjenili";
							thumbsDown.alt = "Već ste ocjenili";
							
							// Handle images
							if (gradeLevel > 0)
							{
								thumbsUp.src = "img/btn.thumbsUp.on.png";
								thumbsDown.src = "img/btn.thumbsDown.off.png";
							}
							else
							{
								thumbsUp.src = "img/btn.thumbsUp.off.png";
								thumbsDown.src = "img/btn.thumbsDown.on.png";
							}
						}
					}
				}
			}
		);
	}
	gradingComment = false;
}
function DeleteComment(uniqueId, holderId, loadingId, commentId, channelId, videoId, page, commentListSizeType, rows)
{
	var loadUrl = "_ajaxCalls/DeleteComment.aspx?commentId=" + commentId + "&channelId=" + channelId + "&videoId=" + videoId;

	//if (loading == false) 
	{
		//loading = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					loading = false;
				}
    			,'onError':function(req)
				{
					loading = false;
				}
				,'onSuccess':function(req)
				{
					loading = false;
					if (req.responseText == "status=deleted&error=0")
					{
						// Reloading comments
						LoadComments(uniqueId, holderId, loadingId, 1, channelId, videoId, page, commentListSizeType, rows);
					}
				}
			}
		);
	}
	loading = false;
}

var commenting = new Array();
function IsTimerActive()
{
	var isActive = true;
	if(commenting != undefined && commenting != null && commenting.length > 0)
	{
		for(var index = 0; index < commenting.length; index++)
		{
			var isCommenting = commenting[index];
			if (isCommenting != undefined && isCommenting != null && isCommenting == true)
			{
				isActive = false;
				break;
			}
		}
	}
	return isActive;
}
function SetCommenting(index, opened)
{
	if (index >= 0)
	{
		commenting[index] = opened;
	}
}

var savingChannelCssStyle = false;
function SaveChannelCssStyle()
{
	$('#SaveUserStyles').hide();
	$('#ResetUserStyles').hide();
	
	$('#output').hide();
	var targetForm = document.frmChannelStyle;
	
	// Values set, submiting
	if (AjaxRequest && !savingChannelCssStyle)
	{
		var oldButtonValue = "";
		var objButton = document.getElementById("btnSaveHolder");
		if (objButton)
		{
			oldButtonValue = objButton.innerHTML;
			objButton.innerHTML = "<img src='img/loading.gif' alt=''>";
		}
		status = AjaxRequest.submit
		(
			targetForm,
			{
				'onError':function(req)
				{
					// Error handling
					savingChannelCssStyle = false;
					if(typeof window.DisplayStatus == 'function') DisplayStatus(generalError, true);
					$('#output').show();
					$('#SaveUserStyles').show();
					$('#ResetUserStyles').show();
				}
				,'onTimeout':function(req)
				{
					// Error handling
					savingChannelCssStyle = false;
					if(typeof window.DisplayStatus == 'function') DisplayStatus(generalError, true);
					$('#output').show();
					$('#SaveUserStyles').show();
					$('#ResetUserStyles').show();
				}
				,'onSuccess':function(req)
				{
					savingChannelCssStyle = false;
					if (req.responseText == "status=saved&error=0")
					{
						if(typeof window.DisplayStatus == 'function') DisplayStatus("Stil je snimljen.");
					}
					else
					{
						// Error handling
						if(typeof window.DisplayStatus == 'function') DisplayStatus(generalError, true);
					}
					$('#output').show();
					$('#SaveUserStyles').show();
					$('#ResetUserStyles').show();
				}
			}
		);
		savingChannelCssStyle = false;
		if (objButton && oldButtonValue.length > 0) objButton.innerHTML = oldButtonValue;
		targetForm.reset();
	}
}

var savingComment = false;
// it is used for both Channel and Video comments
function SaveChannelComment(uniqueId, holderId, loadingId, commentNick, commentBody, videoId, channelId, buttonId, rows, commentIdValue, statusHolderId)
{
	var objChannelCommentStatus = document.getElementById(statusHolderId);
	if ((videoId > 0 || channelId > 0) && commentBody.length > 0)
	{
		// Locate form and set values
		var targetForm = document.frmSaveComment;
		if (targetForm)
		{
			if (commentIdValue == null || commentIdValue == undefined || commentIdValue.length <= 0) commentIdValue = 0;
			var objCommentNick = targetForm.rtbCommentNick;
			var objCommentBody = targetForm.rtbCommentBody;
			var objVideoId = targetForm.videoId;
			var objChannelId = targetForm.channelId;
			var objCommentId = targetForm.commentId;
			if (objCommentNick && objCommentBody && objVideoId && objChannelId)
			{
				//var objRadNick = window[commentNick];
				var objRadNick = undefined;
				var objRadNickValue = "";
				if (objRadNick && objRadNick != undefined)
				{
					objRadNickValue = objRadNick.GetValue();
				}
				else
				{
					//objRadNick = document.getElementById(commentNick + "_text");
					objRadNick = document.getElementById(commentNick);
					if (objRadNick && objRadNick != undefined) objRadNickValue = objRadNick.value;
				}
				
				//var objRadBody = window[commentBody];
				var objRadBody = undefined;
				var objRadBodyValue = "";
				if (objRadBody && objRadBody != undefined)
				{
					objRadBodyValue = objRadBody.GetValue();
				}
				else
				{
					//objRadBody = document.getElementById(commentBody + "_text");
					objRadBody = document.getElementById(commentBody);
					if (objRadBody && objRadBody != undefined) objRadBodyValue = objRadBody.value;
				}
				
				if (objRadNickValue && objRadNickValue != undefined && objRadNickValue.length > 0) objCommentNick.value = objRadNickValue;
				if (objRadBodyValue && objRadBodyValue != undefined && objRadBodyValue.length > 0) objCommentBody.value = objRadBodyValue;
				
				objCommentId.value = commentIdValue;
				objVideoId.value = videoId;
				objChannelId.value = channelId;
				
				// Values set, submiting
				if (AjaxRequest && !savingComment)
				{
					var oldButtonValue = "";
					var objButton = document.getElementById(buttonId);
					if (objButton)
					{
						oldButtonValue = objButton.innerHTML;
						objButton.innerHTML = "<img src='img/loading.gif' alt=''>";
					}
					status = AjaxRequest.submit
					(
						targetForm,
						{
							'onError':function(req)
							{
								// Error handling
								savingComment = false;
								if (objChannelCommentStatus) objChannelCommentStatus.innerHTML = generalError;
							}
							,'onTimeout':function(req)
							{
								// Error handling
								savingComment = false;
								if (objChannelCommentStatus) objChannelCommentStatus.innerHTML = generalError;
							}
							,'onSuccess':function(req)
							{
								savingComment = false;
								if (req.responseText == "status=saved&error=0")
								{
									// Saved, reload comment list
									if (uniqueId.length > 0)
									{
										var commentPage = 1;
										if (commentIdValue > 0) commentPage = 0;
										
										ReloadCommentsList(commentPage);	
									}
									//if (objRadBody && objRadBody != undefined) objRadBody.Clear();
									if (objRadBody && objRadBody != undefined) objRadBody.value = "";
									if (objChannelCommentStatus) objChannelCommentStatus.innerHTML = "<span class='commentStatusPositive'>Komentar je snimljen.</span>";
								}
								else if (req.responseText == "status=repeatedComment&error=1")
								{
									// Error handling
									if (objChannelCommentStatus) objChannelCommentStatus.innerHTML = "<span class='commentStatusNegative'>Isti komentar možete objaviti samo jednom!</span>";
								}
								else if (req.responseText == "status=nicknameInUse&error=1")
								{	
									// Error handling
									if (objChannelCommentStatus) objChannelCommentStatus.innerHTML = "<span class='commentStatusNegative'>Nadimak koji ste upisali koristi registrirani korisnik! Odaberite neki drugi!</span>";
								}
								else
								{
									// Error handling
									if (objChannelCommentStatus) objChannelCommentStatus.innerHTML = "<span class='commentStatusNegative'>" + generalError + "</span>";
								}
							}
						}
					);
					savingComment = false;
					if (objButton && oldButtonValue.length > 0) objButton.innerHTML = oldButtonValue;
					targetForm.reset();
				}
			} 
		}
	}
	else
	{
		// Error handling
		savingComment = false;
		if (objChannelCommentStatus) objChannelCommentStatus.innerHTML = generalError;
	}
	savingComment = false;
}
function LoadMyVideos(uniqueId, holderId, loadingId, mainIndex, subIndex, page, rows, layout, closureFn)
{
	LoadData(holderId, loadingId, "_ajaxCallsMyVideos.aspx?mainIndex=" + mainIndex + "&subIndex=" + subIndex + "&rows=" + rows + "&page=" + page + "&holderUniqueId=" + uniqueId + "&layout=" + layout, null, closureFn);
}

function LoadVideoFavorites(uniqueId, holderId, loadingId, mainIndex, subIndex, page, rows, layout)
{
	LoadData(holderId, loadingId, "_ajaxCallsVideoFavorites.aspx?mainIndex=" + mainIndex + "&subIndex=" + subIndex + "&rows=" + rows + "&page=" + page + "&holderUniqueId=" + uniqueId + "&layout=" + layout);
}

function LoadSearchResults(uniqueId, holderId, loadingId, page, rows, searchTerm, searchType, searchCategory, searchGradeRange, searchDurationRange, searchVideoCount, searchPublishedRange, searchInTable, hideGrades, showChannel)
{
	LoadData(holderId, loadingId, "_ajaxCallsSearch.aspx?rtbSearchTerm=" + escape(searchTerm) + "&rbSearchType=" + searchType + "&rcbSearchCategory=" + searchCategory + "&rcbSearchGradeRange=" + searchGradeRange + "&rcbSearchDurationRange=" + searchDurationRange + "&rcbSearchVideoCount=" + searchVideoCount + "&rcbSearchPublishedRange=" + searchPublishedRange + "&rbSearchInTable=" + searchInTable + "&rows=" + rows + "&hideGrades=" + hideGrades + "&showChannel=" + showChannel + "&page=" + page + "&holderUniqueId=" + uniqueId);
}
function LoadChannelList(uniqueId, holderId, loadingId, mainIndex, subIndex, page, rows, layout, categoryId, videosPerRow, showCategory, categoryTitle)
{
	LoadData(holderId, loadingId, "_ajaxCallsChannels.aspx?mainIndex=" + mainIndex + "&subIndex=" + subIndex + "&categoryId=" + categoryId + "&rows=" + rows + "&videosPerRow=" + videosPerRow + "&page=" + page + "&holderUniqueId=" + uniqueId + "&layout=" + layout + "&showCategory=" + showCategory + "&categoryTitle=" + categoryTitle);
}
function LoadFriends(uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout, closureFn)
{
	LoadData(holderId, loadingId, "_ajaxCallsFriends.aspx?mainIndex=" + mainIndex + "&rows=" + rows + "&page=" + page + "&layout=" + layout + "&holderUniqueId=" + uniqueId, null, closureFn);	
}
function LoadPollForm(uniqueId, holderId, loadingId, pollId, closureFn)
{
	LoadData(holderId, loadingId, "_ajaxCallsPollForm.aspx?pollId=" + pollId, null, closureFn);
}
function LoadSubscriptions(uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout, categoryId)
{
	LoadData(holderId, loadingId, "_ajaxCallsSubscriptions.aspx?mainIndex=" + mainIndex + "&rows=" + rows + "&page=" + page + "&layout=" + layout + "&categoryId=" + categoryId + "&holderUniqueId=" + uniqueId);
}
var removingFriend = false;
function RemoveFriend(friendId, uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout)
{
	var loadUrl = "_ajaxCalls/RemoveFriend.aspx?friendId=" + friendId + "&mainIndex=" + mainIndex;
	if (removingFriend == false) 
	{
		removingFriend = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					removingFriend = false;
				}
    			,'onError':function(req)
				{
					removingFriend = false;
				}
				,'onSuccess':function(req)
				{
					removingFriend = false;
					if (req.responseText == "status=removed&error=0")
					{
						// Reload friends list
						LoadFriends(uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout);
					}
					
				}
			}
		);
	}
	removingFriend = false;
}

var removingSubscription = false;
function RemoveSubscription(subscriptionId, uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout, categoryId)
{
	var loadUrl = "_ajaxCalls/RemoveSubscription.aspx?subscriptionId=" + subscriptionId;
	if (removingSubscription == false) 
	{
		removingSubscription = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					removingSubscription = false;
				}
    			,'onError':function(req)
				{
					removingSubscription = false;
				}
				,'onSuccess':function(req)
				{
					removingSubscription = false;
					if (req.responseText == "status=removed&error=0")
					{
						// Reload friends list
						LoadSubscriptions(uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout, categoryId);
					}
					
				}
			}
		);
	}
	removingSubscription = false;
}
var sortingFriends = false;
function SortFriends(sortedFriends, divId, reportId)
{
	var loadUrl = "_ajaxCalls/SortFriends.aspx?sortedFriends=" + sortedFriends;
	if (sortingFriends == false) 
	{
		sortingFriends = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					sortingFriends = false;
					if (reportId && reportId.length > 0)
					{
						var reportObj = GetObjById(reportId);
						if (reportObj)
						{
							reportObj.innerHTML = "<span class='neumatikErrorMessage'>Došlo je do greške! Molimo pokušajte kasnije.</span>";
							reportObj.style.display = "block";
						}
					}
				}
    			,'onError':function(req)
				{
					sortingFriends = false;
					if (reportId && reportId.length > 0)
					{
						var reportObj = GetObjById(reportId);
						if (reportObj)
						{
							reportObj.innerHTML = "<span class='neumatikErrorMessage'>Došlo je do greške! Molimo pokušajte kasnije.</span>";
							reportObj.style.display = "block";
						}
					}
				}
				,'onSuccess':function(req)
				{
					sortingFriends = false;
					if (req.responseText == "status=saved&error=0")
					{
						// Report to user
						if (divId && divId.length > 0)
						{
							var divObj = GetObjById(divId);
							if (divObj)
							{
								divObj.style.display = "none";
							}
						}
						if (reportId && reportId.length > 0)
						{
							var reportObj = GetObjById(reportId);
							if (reportObj)
							{
								reportObj.innerHTML = "Odabir je uspješno snimljen!";
								reportObj.style.display = "block";
							}
						}
						if (reportId && reportId.length > 0)
						{
							var reportObj = GetObjById(reportId);
							if (reportObj)
							{
								reportObj.innerHTML = "<span class='neumatikReportMessage'>Odabir je uspješno snimljen!</span>";
								reportObj.style.display = "block";
							}
						}
					}
					else
					{
						if (reportId && reportId.length > 0)
						{
							var reportObj = GetObjById(reportId);
							if (reportObj)
							{
								reportObj.innerHTML = "<span class='neumatikErrorMessage'>Došlo je do greške! Molimo pokušajte kasnije.</span>";
								reportObj.style.display = "block";
							}
						}
					}
				}
			}
		);
	}
	sortingFriends = false;
}
var sortingVideos = false;
function SortVideos(sortedVideos, divId, reportId)
{
	var loadUrl = "_ajaxCalls/SortVideos.aspx?sortedVideos=" + sortedVideos;
	if (sortingVideos == false) 
	{
		sortingVideos = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					sortingVideos = false;
					if (reportId && reportId.length > 0)
					{
						var reportObj = GetObjById(reportId);
						if (reportObj)
						{
							reportObj.innerHTML = "<span class='neumatikErrorMessage'>Došlo je do greške! Molimo pokušajte kasnije.</span>";
							reportObj.style.display = "block";
						}
					}
				}
    			,'onError':function(req)
				{
					sortingVideos = false;
					if (reportId && reportId.length > 0)
					{
						var reportObj = GetObjById(reportId);
						if (reportObj)
						{
							reportObj.innerHTML = "<span class='neumatikErrorMessage'>Došlo je do greške! Molimo pokušajte kasnije.</span>";
							reportObj.style.display = "block";
						}
					}
				}
				,'onSuccess':function(req)
				{
					sortingVideos = false;
					if (req.responseText == "status=saved&error=0")
					{
						// Report to user
						if (divId && divId.length > 0)
						{
							var divObj = GetObjById(divId);
							if (divObj)
							{
								divObj.style.display = "none";
							}
						}
						if (reportId && reportId.length > 0)
						{
							var reportObj = GetObjById(reportId);
							if (reportObj)
							{
								reportObj.innerHTML = "<span class='neumatikReportMessage'>Odabir je uspješno snimljen!</span>";
								reportObj.style.display = "block";
							}
						}
					}
					else
					{
						if (reportId && reportId.length > 0)
						{
							var reportObj = GetObjById(reportId);
							if (reportObj)
							{
								reportObj.innerHTML = "<span class='neumatikErrorMessage'>Došlo je do greške! Molimo pokušajte kasnije.</span>";
								reportObj.style.display = "block";
							}
						}
					}
				}
			}
		);
	}
	sortingVideos = false;
}

var savingPoll = false;
function SavePoll()
{
	var targetForm = document.frmUserPoll;
	
	if ($("#submitButton")) $("#submitButton").hide();
	if ($("#deleteButton")) $("#deleteButton").hide();
	// Values set, submiting
	if (AjaxRequest && !savingPoll)
	{
		status = AjaxRequest.submit
		(
			targetForm,
			{
				'onError':function(req)
				{
					// Error handling
					savingPoll = false;
					if(typeof window.DisplayStatus == 'function') DisplayStatus(generalError, true);
					if ($("#submitButton")) $("#submitButton").show();
					if ($("#deleteButton")) $("#deleteButton").show();
				}
				,'onTimeout':function(req)
				{
					// Error handling
					savingPoll = false;
					if(typeof window.DisplayStatus == 'function') DisplayStatus(generalError, true);
					if ($("#submitButton")) $("#submitButton").show();
					if ($("#deleteButton")) $("#deleteButton").show();
				}
				,'onSuccess':function(req)
				{
					savingPoll = false;
					if (req.responseText.indexOf("status=saved&error=0") == 0)
					{
						//extract newID
						var newId = req.responseText.replace("status=saved&error=0&newID=", "");
						newId = newId*1;
						if(typeof window.DisplayStatus == 'function')
						{
							if (newId > 0)
							{ 
								DisplayStatus("Anketa je snimljena.", false, newId);
							}
							else
							{
								DisplayStatus("Anketa je izbrisana.", false, newId);
								setTimeout("ReloadPollForm('', 0)", 2500);
							}
						}
					}
					else
					{
						// Error handling
						if(typeof window.DisplayStatus == 'function') DisplayStatus(generalError, true);
					}
					if ($("#submitButton")) $("#submitButton").show();
					if ($("#deleteButton")) $("#deleteButton").show();
				}
			}
		);
		savingPoll = false;
		targetForm.reset();
	}
}

var acceptingFriend = false;
function AcceptFriend(friendId, uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout)
{
	var loadUrl = "_ajaxCalls/AcceptFriend.aspx?friendId=" + friendId;
	if (acceptingFriend == false) 
	{
		acceptingFriend = true;
		AjaxRequest.get
		( 
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					acceptingFriend = false;
				}
    			,'onError':function(req)
				{
					acceptingFriend = false;
				}
				,'onSuccess':function(req)
				{
					acceptingFriend = false;
					if (req.responseText == "status=saved&error=0")
					{
						// Reload friends list
						LoadFriends(uniqueId, holderId, loadingId, mainIndex, page, rows, recordcount, layout);
					}
					
				}
			}
		);
	}
	acceptingFriend = false;
}

var addingToFriend = false;
function AddToFriend(channelOwnerId, imageId, newImageSrc)
{
	var loadUrl = "_ajaxCalls/AddToFriend.aspx?channelOwnerId=" + channelOwnerId;
	if (addingToFriend == false) 
	{
		addingToFriend = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					addingToFriend = false;
				}
    			,'onError':function(req)
				{
					addingToFriend = false;
				}
				,'onSuccess':function(req)
				{
					addingToFriend = false;
					if (req.responseText == "status=saved&error=0")
					{
						// Report to user
						if (imageId && imageId.length > 0 && newImageSrc && newImageSrc.length > 0)
						{
							var imgObj = GetObjById(imageId);
							if (imgObj)
							{
								imgObj.src = newImageSrc;
							}
						}
					}
				}
			}
		);
	}
	addingToFriend = false;
}

var subscribing = false;
function SubscribeChannel(channelId, imageId, newImageSrc)
{
	var loadUrl = "_ajaxCalls/SubscribeToChannel.aspx?channelId=" + channelId;
	if (subscribing == false) 
	{
		subscribing = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					subscribing = false;
				}
    			,'onError':function(req)
				{
					subscribing = false;
				}
				,'onSuccess':function(req)
				{
					subscribing = false;
					if (req.responseText == "status=saved&error=0")
					{
						// Report to user
						if (imageId && imageId.length > 0 && newImageSrc && newImageSrc.length > 0)
						{
							var imgObj = GetObjById(imageId);
							if (imgObj)
							{
								imgObj.src = newImageSrc;
							}
						}
					}
					
				}
			}
		);
	}
	subscribing = false;
}

var checkingNick = false;
function CheckNicknameAvailability(userNickname, imageId, correctImgSrc, wrongImgSrc, correctToolTip, wrongToolTip)
{
	var loadUrl = "_ajaxCalls/checkValidNickname.aspx?userNickname=" + userNickname;
	var toolTip = "";
	var imgSrc = "";
	nickIsAvailable = false;
	if (checkingNick == false) 
	{
		checkingNick = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					checkingNick = false;
				}
    			,'onError':function(req)
				{
					checkingNick = false;
				}
				,'onSuccess':function(req)
				{
					checkingNick = false;
					var nickAvailable = false;
					if (req.responseText == "status=badnick&error=1")
					{
						toolTip = wrongToolTip;
						imgSrc = wrongImgSrc;
						nickAvailable = false;
					}
					else
					{
						toolTip = correctToolTip;
						imgSrc = correctImgSrc;
						nickAvailable = true;
					}
					
					if (imageId && imageId.length > 0 && toolTip.length > 0 && imgSrc.length > 0)
					{
						var imgObj = GetObjById(imageId);
						if (imgObj)
						{
							imgObj.src = imgSrc;
							imgObj.alt = toolTip;
							imgObj.title = toolTip;
						}
					}
				}
				
			}
		);
	}
	checkingNick = false;
}

var addingVideoFavorites = false;
function AddToVideoFavorites(videoId, holderId)
{
	var loadUrl = "_ajaxCalls/AddToVideoFavorites.aspx?videoId=" + videoId;
	if (addingVideoFavorites == false) 
	{
		addingVideoFavorites = true;
		AjaxRequest.get
		(
			{
				'url': loadUrl
				,'timeout':20000
				,'onLoading':function(req)
				{
				}
   				,'onTimeout':function(req)
				{
					addingVideoFavorites = false;
				}
    			,'onError':function(req)
				{
					addingVideoFavorites = false;
				}
				,'onSuccess':function(req)
				{
					addingVideoFavorites = false;
					if (req.responseText == "status=saved&error=0")
					{
						// Report to user
						if (holderId && holderId.length > 0)
						{
							Hide(holderId);
						}
					}
					
				}
			}
		);
	}
	addingVideoFavorites = false;
}
var savingReport = false;
function ReportUser(commentBody, videoId, channelId, buttonId, statusId)
{
	if ((videoId > 0 || channelId > 0) && commentBody.length > 0)
	{
		// Locate form and set values
		var targetForm = document.frmReportUser;
		if (targetForm)
		{
			var objCommentBody = targetForm.rtbReportUserBody;
			var objVideoId = targetForm.videoId;
			var objChannelId = targetForm.channelId;
			if (objCommentBody && objVideoId && objChannelId)
			{
				var objRadBody = window[commentBody];
				if (objRadBody && objRadBody != undefined) objCommentBody.value = objRadBody.GetValue();
				objVideoId.value = videoId;
				objChannelId.value = channelId;
				
				// Values set, submiting
				if (AjaxRequest && !savingReport)
				{
					var oldButtonValue = "";
					var objButton = document.getElementById(buttonId);
					if (objButton)
					{
						oldButtonValue = objButton.innerHTML;
						objButton.innerHTML = "<img src='img/loading.gif' alt=''>";
					}
					var objStatus = document.getElementById(statusId);
					status = AjaxRequest.submit
					(
						targetForm,
						{
							'onError':function(req)
							{
								// Error handling
								savingReport = false;
								if (objStatus) objStatus.innerHTML = "<font color='red'>Greška.</font>";
							}
							,'onTimeout':function(req)
							{
								// Error handling
								savingReport = false;
								if (objStatus) objStatus.innerHTML = "<font color='red'>Greška.</font>";
							}
							,'onSuccess':function(req)
							{
								savingReport = false;
								if (req.responseText == "status=saved&error=0")
								{
									// Saved, reload comment list
									if (objRadBody && objRadBody != undefined) objRadBody.Clear();
									if (objStatus) objStatus.innerHTML = "Poslano.";
								}
								else
								{
									// Error handling
									if (objStatus) objStatus.innerHTML = "<font color='red'>Greška.</font>";
								}
							}
						}
					);
					
					savingReport = false;
					if (objButton && oldButtonValue.length > 0) objButton.innerHTML = oldButtonValue;
					targetForm.reset();
				}
			} 
		}
	}
	else
	{
		// Error handling
		savingReport = false;
	}
	savingReport = false;
}

var gradingVideo = false;
function GradeUserVideo(grade, videoId, currentGrade, gradeCount, incrementIndex, oldGrade)//5, 0, 3, 10, 1, 0
{
	var objSendVideoGradeStatus = document.getElementById("videoGradeStatus");
	var objVideoGradeCurrent = document.getElementById("videoGradeCurrent");
	var objVotedGradeCount = document.getElementById("votedGradeCount");
	
	if (grade > 0 && grade <= 5 && currentGrade >= 0 && gradeCount >= 0 && videoId > 0 && !gradingVideo)
	{
		var formObj = document.forms["frmGradeVideo"];
		if (formObj && AjaxRequest)
		{
			var obSendId = formObj.videoId;
			var obSendRate = formObj.rate;
			if (oldGrade > 0) incrementIndex = 0;
			currentGrade = currentGrade * gradeCount;
			if (incrementIndex > 0) gradeCount = gradeCount + incrementIndex;
			if (oldGrade > 0)
			{
				currentGrade = currentGrade - oldGrade;
			}
			var recalculatedGrade = Math.round(((currentGrade + grade)/gradeCount)*10)/10;// One decimal
			
			if (recalculatedGrade > 0 && obSendId && obSendRate)
			{
				obSendId.value = videoId;
				obSendRate.value = grade;
				
				// Formating
				var reformated = recalculatedGrade.toString().replace(",","");
				reformated = reformated.replace(".",",");
				
				// Show reformated grade
				
				// Send form
				status = AjaxRequest.submit
				(
					formObj,
					{
						'onError':function(req)
						{
							// Error handling
							gradingVideo = false;
							if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = generalError;
						}
						,'onTimeout':function(req)
						{
							// Error handling
							gradingVideo = false;
							if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = generalError;
						}
						,'onSuccess':function(req)
						{
							gradingVideo = false;
							if (req.responseText == "status=graded&error=0")
							{
								// Saved, reload comment list
								if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = "Ocijenili ste sa <span class='important'>" + grade + "</span>";
								if (objVideoGradeCurrent) objVideoGradeCurrent.innerHTML = reformated;
								if (incrementIndex > 0)
								{
									var current = parseInt(objVotedGradeCount.innerHTML);
									if (objVotedGradeCount) objVotedGradeCount.innerHTML = parseInt(current + incrementIndex);
								}
							}
							else if (req.responseText == "status=allreadyVoted&error=1")
							{
								// Error handling
								if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = "<font color='red'>Već ste glasali</font>";
							}
							else
							{
								// Error handling
								if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = generalError;
							}
							
						}
					}
				);
			}
			else
			{
				// Error
				if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = generalError;
			}
		}
		else
		{
			// Error
			if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = generalError;
		}
	}
	else
	{
		// Error
		if (objSendVideoGradeStatus) objSendVideoGradeStatus.innerHTML = generalError;
	}
	gradingVideo = false;
}

function ReloadPlaylistOptions(title, videoId, autoplayId, autoremoveId)
{
	if (videoId > 0 && title.length > 0 &&  autoplayId.length > 0 && autoremoveId.length > 0)
	{
		var objAutoplay = document.getElementById(autoplayId);
		var objAutoremove = document.getElementById(autoremoveId);
		var autoplayValue = 0;
		var autoremoveValue = 0;
		if (objAutoplay && objAutoplay.checked) autoplayValue = 1;
		if (objAutoremove && objAutoremove.checked) autoremoveValue = 1;
		var formatedUrl = title + "-Playlist_" + videoId + "_" + autoplayValue + "_" + autoremoveValue + ".aspx";
		GetUrl(formatedUrl);
	}
}

function SavePannelSettings(pannelIndex, pannelId, showPannel)
{
	if (pannelId.length > 0)
	{
		if (showPannel)
		{
			showPannel = Number(showPannel);
		}
		else
		{
			showPannel = -1;
		}
		var objPannel = document.getElementById(pannelId);
		if (objPannel)
		{
			if (showPannel == -1)
			{
				if (objPannel.style.display == "block") showPannel = 1;
			}
			else
			{
				showPannel = 0;
			}
			LoadData("", "", "_ajaxCalls/SavePannelDisplaySettings.aspx?pannelIndex=" + pannelIndex + "&showPannel=" + showPannel);
		}
	}
}

function LoginKeyPress(sender, args)
{
	if (args.KeyCode == 13)
	{
		if (sender && sender.ClientID)
		{
			var parentContainer = sender.ClientID;
			parentContainer = parentContainer.replace("rtbUsername", "");
			parentContainer = parentContainer.replace("rtbPassword", "");
			SubmitLogin(parentContainer + 'rtbUsername', parentContainer + 'rtbPassword');
		}
	}
}

function SearchKeyPress(sender, args)
{
	if (args.KeyCode == 13)
	{
		if (sender && sender.ClientID)
		{
			var parentContainer = sender.ClientID;
			parentContainer = parentContainer.replace("rtbSearchTerm", "");
			parentContainer = parentContainer.replace("rcbSearchCategory", "");
			parentContainer = parentContainer.replace("rcbSearchGradeRange", "");
			parentContainer = parentContainer.replace("rcbSearchDurationRange", "");
			parentContainer = parentContainer.replace("rcbSearchVideoCount", "");
			parentContainer = parentContainer.replace("rcbSearchPublishedRange", "");
			SubmitAdvancedSearch(parentContainer + 'rtbSearchTerm', 'searchType', parentContainer + 'rcbSearchCategory', parentContainer + 'rcbSearchGradeRange', parentContainer + 'rcbSearchDurationRange', parentContainer + 'rcbSearchVideoCount', parentContainer + 'rcbSearchPublishedRange', 'searchInTable');
		}
	}
}

function SearchSimpleKeyPress(sender, args)
{
	if (args.KeyCode == 13)
	{
		if (sender && sender.ClientID)
		{
			SubmitSimpleSearch(sender.ClientID);
		}
	}
}

function LostPasswordKeyPress(sender, args)
{
	if (args.KeyCode == 13)
	{
		if (sender && sender.ClientID)
		{
			SubmitLostPassword(sender.ClientID);
		}
	}
}

function SetCss(elementId, cssId)
{
	var elementObj = document.getElementById(elementId);
	if (elementObj)
	{
		elementObj.className = cssId;
	}
}


function PositionPageCover(pageCoverId, pageContainerId)
{
	if (pageCoverId.length > 0)
	{
		var objCover = document.getElementById(pageCoverId);
		if (objCover)
		{
			var objMain = document.getElementById(pageContainerId);
			//if (objMain && objMain.style.display != "none")
			if (objMain)
			{
				var winHeight = objMain.offsetHeight;
				if (winHeight > 0)
				{
					objCover.style.height = winHeight;
				}
			}
		}
	}
}

function ToggleImage(objImage, onImageSrc, offImageSrc)
{
	if (objImage)
	{
		var currentImageName = objImage.src;
		var lastIndex = currentImageName.lastIndexOf("/");
		var imgSrcPath = currentImageName.substring(0, lastIndex + 1);
		currentImageName = currentImageName.substring(lastIndex + 1).toLowerCase();
		
		var localLoginForm = document.frmLocalLogin;
		var ssoLoginForm = document.frmSsoLogin;
			
		if (currentImageName == onImageSrc.toLowerCase())
		{
			if (localLoginForm) localLoginForm.remember.value = "0";
			if (ssoLoginForm) ssoLoginForm.remember.value = "0";
			objImage.src = imgSrcPath + offImageSrc;
		}
		else
		{
			if (localLoginForm) localLoginForm.remember.value = "1";
			if (ssoLoginForm) ssoLoginForm.remember.value = "1";
			objImage.src = imgSrcPath + onImageSrc;
		}
	}
}
function ChangeImage(imageId, imageSrc, addTimestamp)
{
	if(imageId && imageId.length > 0 && imageSrc && imageSrc.length > 0)
	{
		var objImage = document.getElementById(imageId);
		if (objImage)
		{
			var stamp = "";
			if (addTimestamp == true)
			{
				var now = new Date();
				stamp = "?uid=" + now.getFullYear() + now.getMonth() + now.getDay() + now.getHours() + now.getMinutes() + now.getSeconds() + now.getMilliseconds();
			}

			objImage.src = imageSrc + stamp;
		}
	}
}

function WindowHeight()
{
	var winHeight = 0;
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		winHeight = window.innerHeight;
	}
	else if( document.documentElement && document.documentElement.clientHeight )
	{
		//IE 6+ in 'standards compliant mode'
		winHeight = document.documentElement.clientHeight;
	} else if( document.body && document.body.clientHeight )
	{
		//IE 4 compatible
		winHeight = document.body.clientHeight;
  }
  return winHeight;
}

function WindowWidth()
{
	var winWidth = 0;
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		winWidth = window.innerWidth;
	}
	else if( document.documentElement && document.documentElement.clientWidth )
	{
		//IE 6+ in 'standards compliant mode'
		winWidth = document.documentElement.clientWidth;
	} else if( document.body && document.body.clientWidth )
	{
		//IE 4 compatible
		winWidth = document.body.clientWidth;
  }
  return winWidth;
}
function ChangeBorder(targetId, colorL, colorT, colorR, colorB)
{
	var obj = document.getElementById(targetId);
	if(obj)
	{
		obj.style.borderLeft = "1px #" + colorL + " solid";
		obj.style.borderTop = "1px #" + colorT + " solid";
		obj.style.borderRight = "1px #" + colorR + " solid";
		obj.style.borderBottom = "1px #" + colorB + " solid";
	}
}
function MoveBanner(srcBanner, dstBanner)
{
	var objSrc = GetObjById(srcBanner); 
	if (objSrc != null)	InsertText(dstBanner, objSrc.innerHTML);
}
function RefreshComments(){}
/* START: USED FOR FLASH FRIENDS NAV !!*/
var previousFriendArrowEnabled = 0;
var nextFriendArrowEnabled = 0;
function NextFriends()
{
	if (Number(nextFriendArrowEnabled) == 1)
	{
		var swf = navigator.appName.indexOf("Microsoft") != -1 ? window["FriendsSwf"] : document["FriendsSwf"];
		if(swf && swf.MoveNext) swf.MoveNext();
	}
}
function PreviousFriends()
{
	if (Number(previousFriendArrowEnabled) == 1)
	{
		var swf = navigator.appName.indexOf("Microsoft") != -1 ? window["FriendsSwf"] : document["FriendsSwf"];
		if(swf && swf.MovePrevious) swf.MovePrevious();
	}
}
function SetFriendsNav(previousStatus, nextStatus)
{
	if (previousStatus != null && previousStatus != undefined && (Number(previousStatus) == 0 || Number(previousStatus) == 1))
	{
		var previousArrow = GetObjById("previousFriendArrow");
		if (previousArrow != null)
		{
			if (Number(previousStatus) == 1)
			{
				//previousArrow.attachEvent("onclick", PreviousFriends);
				previousFriendArrowEnabled = 1;
				previousArrow.src = "img/arrowTabLeft.png";
				previousArrow.className = "pointer";
			}
			else
			{
				//previousArrow.attachEvent("onclick", null);
				previousFriendArrowEnabled = 0;
				previousArrow.src = "img/arrowTabLeftOff.png";
				previousArrow.className = "";
			}
		}
	}
	if (nextStatus != null && nextStatus != undefined && (Number(nextStatus) == 0 || Number(nextStatus) == 1))
	{
		var nextArrow = GetObjById("nextFriendArrow");
		if (nextArrow != null)
		{
			if (Number(nextStatus) == 1)
			{
				//nextArrow.attachEvent("onclick", NextFriends);
				nextFriendArrowEnabled = 1;
				nextArrow.src = "img/arrowTabRight.png";
				nextArrow.className = "pointer";
			}
			else
			{
				//nextArrow.attachEvent("onclick", null);
				nextFriendArrowEnabled = 0;
				nextArrow.src = "img/arrowTabRightOff.png";
				nextArrow.className = "";
			}
		}
	}
}
/* END: USED FOR FLASH FRIENDS NAV !!*/
/* START: USED IN CSS CONFIGURATOR !!*/
function CollectStyles()// Used in flash
{
	var out = new Array();
	/*
	var headerTitle = $('.USER_tabHeaderTitle');
	out.push({selector: ".USER_tabHeaderTitle", css:"font-family: " + TranslateFont(headerTitle.css('font-family')) + ";color: #" + RgbToHex(GetColor(headerTitle.css('color'))) + ";font-size: " + headerTitle.css('font-size') + ";font-weight: " + headerTitle.css('font-weight') + ";"});
	
	var tabBorder = $('.USER_tabBorder');
	out.push({selector: ".USER_tabBorder", css:"border-top-width: " + tabBorder.css('border-top-width') + ";border-top-style: " + tabBorder.css('border-top-style') + ";border-top-color: #" + RgbToHex(GetColor(tabBorder.css('border-top-color'))) + ";"});
	*/
	var usrFriendTitle = $('a.USER_friendTitle');
	out.push({selector: "a.USER_friendTitle:link", css:"color: #" + RgbToHex(GetColor(usrFriendTitle.css('color'))) + ";font-size: " + usrFriendTitle.css('font-size') + ";font-weight: " + usrFriendTitle.css('font-weight') + ";"});
	var swf = navigator.appName.indexOf("Microsoft") != -1 ? window["FriendsSwf"] : document["FriendsSwf"];
	if(swf && swf.SendStyles) swf.SendStyles(out);
}
function TranslateFont(fnt)// Unify font names for all browsers
{
	if (fnt != undefined)
	{
		var re = new RegExp("['\"]?", "g");
		fnt = fnt.replace(re, "");
		var fntList = fnt.split(",");
		if (fntList != undefined && fntList != null && fntList.length > 0)
		{
			var tagetFnt = fntList[0].toLowerCase();
			var fnts = "arial,helvetica,sans-serif";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "arial black,gadget,sans-serif";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "comic sans ms,cursive";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "courier new,vourier,monospace";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "georgia,times new roman,times,serif";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "tahoma,geneva,sans-serif";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "times new roman,times,serif";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "trebuchet ms,arial,helvetica,sans-serif";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			fnts = "verdana,arial,helvetica,sans-serif";
			if (("," + fnts + ",").indexOf(("," + tagetFnt + ",")) >= 0) return fnts;
			return "";
		}
	}
}
function TranslatePosition(pos)// Unify background position for all browsers + hack for opera 
{
	if (pos != undefined)
	{
		pos = pos.toString().toLowerCase();
		if (pos.indexOf("px") >= 0)// Background position for Opera
		{
			var re = new RegExp("[px]?", "g");
			pos = pos.replace(re, "");
			var posList = pos.split(" ");
			if (posList != undefined && posList != null && posList.length > 0)
			{
				// Get centered marker
				var marker = $("#bkgPosMarker").css("background-position").toString().toLowerCase();
				re = new RegExp("[px]?", "g");
				marker = marker.replace(re, "");
				marker = Number(marker.split(" ")[0]);
				pos = "";
				if (Number(posList[0]) <= 0) pos = "left";
				if (Number(posList[0]) >= marker - 10 && Number(posList[0]) <= marker + 10 ) pos = "center";
				if (Number(posList[0]) > marker + 10) pos = "right";
				if (pos.length > 0)
				{
					if (Number(posList[1]) <= 0) pos = pos + " top";
					if (Number(posList[1]) >= marker - 10 && Number(posList[1]) <= marker + 10 ) pos = pos + "center";
					if (Number(posList[1]) > marker + 10) pos = pos + "top";
				}
			}
		}
		else
		{
			switch(pos)
			{
				case "50% 100%":
					pos = "center bottom";
					break;
				case "0% 100%":
					pos = "left bottom";
					break;
				case "100% 100%":
					pos = "right bottom";
					break;
				case "50% 50%":
					pos = "center center";
					break;
				case "0% 50%":
					pos = "left center";
					break;
				case "100% 50%":
					pos = "right center";
					break;
				case "50% 0%":
					pos = "center top";
					break;
				case "0% 0%":
					pos = "left top";
					break;
				case "100% 0%":
					pos = "right top";
					break;
				default:
					pos = "";
					break;
			}
		}
	}
	return pos;
}
function GetColor(cssColor){var targetColor = "";if (cssColor != undefined && cssColor != undefined && cssColor.length > 0){var re = new RegExp("[#]?", "g");targetColor = cssColor.replace(re, "");}return targetColor;}
function RgbToHex(rgb){if(rgb.indexOf(",") != -1){var col = rgb.substring(4, rgb.length - 1).split(", ");rgb = ToHex(col[0]) + ToHex(col[1]) + ToHex(col[2]);}return rgb;}
function ToHex(N) {if (N==null){return "00";}else{N = parseInt(N); if (N == 0 || isNaN(N)){return "00";}else{N = Math.max(0,N);N = Math.min(N,255);N = Math.round(N);return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);}}}
/* END: USED IN CSS CONFIGURATOR !!*/
var disableHideLeadTitle = 0;
function HideLeadTitle() {  if (Number(disableHideLeadTitle) == 0) setTimeout(ExecuteHideLeadTitle, 100); }
function ExecuteHideLeadTitle() { if (Number(disableHideLeadTitle) == 0) $('#leadVideoTitleContainer').hide() }