// Start ajax
function createRequestObject() {
	var req;

	if (window.XMLHttpRequest) {
		// Firefox, Safari, Opera...
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// Internet Explorer 5+
		req = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		// There is an error creating the object,
		// just as an old browser is being used.
		alert('Problem creating the XMLHttpRequest object');
	}

	return req;
}

// Make the XMLHttpRequest object
var http = createRequestObject();

// POST method
function sendPost(page, data, callFunc) {
	// Open PHP script for requests
	http.abort;
	http.open('post', page, true);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = function() {
		getRespRaw(callFunc);
	}
	http.send(data);
}

// GET method
function sendGet(url, callFunc) {
	// Open PHP script for requests
	http.open('get', url, true);
	http.onreadystatechange = function() {
		getRespRaw(callFunc);
	}
	http.send(null);
}

// Handle Response
function getRespRaw(callBackFunc) {
	if (http.readyState == 4 && http.status == 200) {

		// Text returned from PHP script
		var response = http.responseText;

		// eval(callBackFunc + "'" + escape(response) + "')");
		eval(callBackFunc + response + ")");
	}
}

// ###############################
// DRUGI DIO
// ###############################

// Dodaje novi div
function addElement(inEl, elTag, inHtml, otherD, orderAdd) {
	parentEl = document.getElementById(inEl);
	newEl = document.createElement(elTag);
	/*
	 * if (otherD.id) newEl.setAttribute('id', otherD.id); if (otherD.class)
	 * newEl.setAttribute('class', otherD.id); if (otherD.style)
	 * newEl.setAttribute('style', otherD.style);
	 */
	for (index in otherD)
		newEl.setAttribute(index, otherD[index]);
	
	newEl.innerHTML = inHtml;
//	if (orderAdd == 'reverse')
//		parentEl.insertBefore(newEl, parentEl.firstChild); // Dodaj prvo najnoviji element, stare ispod...
//	else
		parentEl.appendChild(newEl); // Prvo prvi element, onda ostali ispod...
}

// Radi fade div-a
function fadeBox(boX, timeout) {
	setTimeout("$('" + boX + "').fade();", timeout);
}

function coverArea() {
	var heightFullPage = document.body.scrollHeight; // Detekcija visine
														// prikazane stranice
	var heightVisiblePage = document.documentElement.clientHeight;
	var displayHeight;

	if (heightFullPage > heightVisiblePage)
		displayHeight = heightFullPage;
	else
		displayHeight = heightVisiblePage;

	document.getElementById("overlayBox").style.display = ""; // Prikazi
																// "foliju"
	document.getElementById("overlayBox").style.height = displayHeight + "px"; // Setuj
																				// visinu
																				// boxa
																				// za
																				// prekrivanje
																				// prozora

}

function uncoverArea() {
	document.getElementById("overlayBox").style.display = "none";
}

// Plutajuci prozor na ekranu
function floatWindow(contFD) {
	floatBox = document.getElementById('floatBoxA');

	// Visina iskoristenog prozora (prozor koji prikazuje site)
	var pageHeight = document.documentElement.clientHeight;

	// Prikazi box i popuni ga
	floatBox.style.display = "";
	floatBox.innerHTML = contFD;

	// Visina boxa (moze se tek definisati nakon sto se popuni box
	boxHeightS = floatBox.offsetHeight;

	offsetH = pageHeight - boxHeightS;
	newOffsetH = offsetH / 2;

	// Podesi polozaj boxa:
	floatBox.style.top = newOffsetH + "px";
}

// Plutajuci prozor na ekranu
function showLoading() {
	floatBoxL = document.getElementById('loadingA');

	// Visina iskoristenog prozora (prozor koji prikazuje site)
	// var pageHeight = document.body.clientHeight;
	var pageHeight = document.documentElement.clientHeight;

	// Prikazi box i popuni ga
	floatBoxL.style.display = "";
	floatBoxL.innerHTML = '<div class = "ajaxBoxMsg" id="loadingg"><img src = "img/small_load.gif"><br/><br/>Loading</div></div>';

	// Visina boxa (moze se tek definisati nakon sto se popuni box
	boxHeightS = floatBoxL.offsetHeight;

	offsetH = pageHeight - boxHeightS;
	newOffsetH = offsetH / 2;

	// Podesi polozaj boxa:
	floatBoxL.style.top = newOffsetH + "px";
}

// Mali loading img
function smallLoading(position) {
	var loadImg = "<img src = 'img/load.gif' />";

	document.getElementById(position).innerHTML = loadImg;
}

function hideSmallLoading(position) {
	document.getElementById(position).innerHTML = "";
}

// Dodaje sadrzaj
function update(data, name) {
	document.getElementById(name).innerHTML = data;
}

// Otkriva element
function show(id) {
	document.getElementById(id).style.display = '';
}

// Skriva element
function hide(id) {
	document.getElementById(id).style.display = 'none';
}

// ShowHide
function showHide(id) {
	el = document.getElementById(id);
	if (el.style.display == 'none') {
		el.style.display = '';
	} else {
		el.style.display = 'none';
	}
}

/*
 * // Prikazuje loading div function showLoading() { var floatBox =
 * document.getElementById('loadingA'); //var ScrollTop =
 * document.body.scrollTop; var scrnH; //Visina ekrana var scrnNT; //Nova
 * dimenzija
 * 
 * scrnH = screen.height / 3;
 *  /* if (ScrollTop == 0) { if (window.pageYOffset) { ScrollTop =
 * window.pageYOffset; } else { ScrollTop = (document.body.parentElement) ?
 * document.body.parentElement.scrollTop : 0; } }
 * 
 * scrnNT = scrnH + ScrollTop;
 * 
 * 
 * floatBox.style.top=scrnNT+"px";
 * 
 * 
 * scrnNT = scrnH;
 * 
 * floatBox.style.top=scrnNT+"px"; floatBox.style.display = "";
 * floatBox.innerHTML = '<div class = "ajaxBoxMsg" id="loadingg"><img src =
 * "img/small_load.gif"><br/><br/>Loading</div></div>'; }
 */

// Skriva loading div
function hideLoading() {
	var polje = document.getElementById("loadingA");
	polje.style.display = 'none';
}

/* Vraca value selektovanog elementa unutar select menija */
function getSelected(ob) {
	for (i = 0; i < ob.options.length; i++) {
		if (ob.options[i].selected) {
			return ob.options[i].value;
			break;
		}
	}
}

/* Provjerava da li postoji error */
function errorsExists(data) {
	if (data.errors) {
		alert(data.errors);
		return false;
	} else {
		return true;
	}
}

/* Upisuje errors & show done u div */
function sdeToDiv(data) {
	var htmlData = '';

	if (data.errors) {
		htmlData += '<div id="error">' + data.errors;

		if (data.errorLink) {
			htmlData += '<br /><br /><a href="' + data.errorLink + '">Dalje</a>';
		}

		htmlData += '</div>';
	}

	if (data.showDone) {
		htmlData += '<div id="done">' + data.showDone;

		if (data.showDoneLink) {
			htmlData += '<br /><br /><a href="' + data.showDoneLink + '">Dalje</a>';
		}

		htmlData += '</div>';
	}

	if (htmlData) {
		update(htmlData, 'sdeDiv');
		show('sdeDiv');
	}
}

/* Prikazuje errors & show done u alert() */
function sdeToAlert(data) {
	var htmlData = '';

	if (data.errors) {
		alert(data.errors);
	}

	if (data.showDone) {
		alert(data.showDone);
	}
}

/* Ako je string prazan vraca zamjenu */
function ifEmptyReturn(data, ret) {
	if (!data) {
		return ret;
	} else {
		return data;
	}
}

/* Mijenja class elementu */
function changeClass(id, name) {
	document.getElementById(id).className = name;
}

/* Kao php stripslashes() funkcija */
function stripslashes(str) {
	str = str.replace(/\\'/g, '\'');
	str = str.replace(/\\"/g, '"');
	str = str.replace(/\\\\/g, '\\');
	str = str.replace(/\\0/g, '\0');
	return str;
}

/* Kao php nl2br() funkcija */
function nl2br(str) {
	if (typeof (str) == "string")
		return str.replace(/(\r\n)|(\n\r)|\r|\n/g, "<br />");
	else
		return str;
}

/* Kao php urlencode() funkcija */
function urlencode(str) {
	return str.replace(/&/g, '%26');
}

/* Samo brojevi i slova dozvojeni */
function isAlphanumeric(elem, helperMsg) {
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if (elem.value.match(alphaExp)) {
		return true;
	} else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

/* Samo brojevi dozvojeni */
function isNumeric(elem, helperMsg) {
	var numericExpression = /^[0-9]+$/;
	if (elem.value.match(numericExpression)) {
		return true;
	} else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

// Koristim u kombinaciji za ako je prazan text field ili ako se samo spaceovi
// unesu da vrati gresku!
function trim(str) {
	s = str.replace(/^(\s)*/, '');
	s = s.replace(/(\s)*$/, '');
	return s;
}

// Provjera ekstenzije kod uploada fajla... upotreba: <input onChange =
// "typeCheck(this)" name...
function typeCheck(extension) {
	var ext = extension.value.substr(extension.value.length - 3, 3)
			.toLowerCase();
	if (ext !== "jpg" && ext !== "jpeg") {
		alert("Only jpg or jpeg allowed!");
		extension.value = "";
		return false;
	} else
		return true;
}

function typeCheckVideo(extension) {
	var ext = extension.value.substr(extension.value.length - 3, 3)
			.toLowerCase();
	if (ext !== "avi" && ext !== "wmv" && ext !== "mpeg" && ext !== "3gp") {
		alert("Only avi, wmv, mpeg and 3gp allowed!");
		extension.value = "";
	}
}

/**
 * #################################################### FUNC...
 * ####################################################
 */
// Funkcije za chekiranje svih polja u privatnim porukama (pocekta)
function CheckAll() {
	count = document.frm.elements.length;
	for (i = 0; i < count; i++) {
		if (document.frm.elements[i].checked == 1) {
			document.frm.elements[i].checked = 0;
		} else {
			document.frm.elements[i].checked = 1;
		}
	}
}
function UncheckAll() {
	count = document.frm.elements.length;
	for (i = 0; i < count; i++) {
		if (document.frm.elements[i].checked == 1) {
			document.frm.elements[i].checked = 0;
		} else {
			document.frm.elements[i].checked = 1;
		}
	}
}
// -->

//Text limitor za text box
function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}


// qTip - CSS Tool Tips - by Craig Erskine
// http://qrayg.com
//
// Multi-tag support by James Crooke
// http://www.cj-design.com
//
// Inspired by code from Travis Beckham
// http://www.squidfingers.com | http://www.podlob.com
//
// Copyright (c) 2006 Craig Erskine
// Permission is granted to copy, distribute and/or modify this document
// under the terms of the GNU Free Documentation License, Version 1.3
// or any later version published by the Free Software Foundation;
// with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
// A copy of the license is included in the section entitled "GNU
// Free Documentation License".

var qTipTag = "a,label,input,img"; //Which tag do you want to qTip-ize? Keep it lowercase!//
var qTipX = 0; //This is qTip's X offset//
var qTipY = 15; //This is qTip's Y offset//

//There's No need to edit anything below this line//
tooltip = {
  name : "qTip",
  offsetX : qTipX,
  offsetY : qTipY,
  tip : null
}

tooltip.init = function () {
	var tipNameSpaceURI = "http://www.w3.org/1999/xhtml";
	if(!tipContainerID){ var tipContainerID = "qTip";}
	var tipContainer = document.getElementById(tipContainerID);

	if(!tipContainer) {
	  tipContainer = document.createElementNS ? document.createElementNS(tipNameSpaceURI, "div") : document.createElement("div");
		tipContainer.setAttribute("id", tipContainerID);
	  document.getElementsByTagName("body").item(0).appendChild(tipContainer);
	}

	if (!document.getElementById) return;
	this.tip = document.getElementById (this.name);
	if (this.tip) document.onmousemove = function (evt) {tooltip.move (evt)};

	var a, sTitle, elements;
	
	var elementList = qTipTag.split(",");
	for(var j = 0; j < elementList.length; j++)
	{	
		elements = document.getElementsByTagName(elementList[j]);
		if(elements)
		{
			for (var i = 0; i < elements.length; i ++)
			{
				a = elements[i];
				sTitle = a.getAttribute("title");				
				if(sTitle)
				{
					a.setAttribute("tiptitle", sTitle);
					a.removeAttribute("title");
					a.removeAttribute("alt");
					a.onmouseover = function() {tooltip.show(this.getAttribute('tiptitle'))};
					a.onmouseout = function() {tooltip.hide()};
				}
			}
		}
	}
}

tooltip.move = function (evt) {
	var x=0, y=0;
	if (document.all) {//IE
		x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
		y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		x += window.event.clientX;
		y += window.event.clientY;
		
	} else {//Good Browsers
		x = evt.pageX;
		y = evt.pageY;
	}
	this.tip.style.left = (x + this.offsetX) + "px";
	this.tip.style.top = (y + this.offsetY) + "px";
}

tooltip.show = function (text) {
	if (!this.tip) return;
	this.tip.innerHTML = text;
	this.tip.style.display = "block";
}

tooltip.hide = function () {
	if (!this.tip) return;
	this.tip.innerHTML = "";
	this.tip.style.display = "none";
}

//window.onload = function () {
//	tooltip.init ();
//}


// funkcija kod dodavanja vijesti box
var boxs = new Array("box1", "box2");

function showBox(name) {
	for (i = 0; i < boxs.length; i++) {
		document.getElementById(boxs[i]).style.display = "none";
	}

	document.getElementById(name).style.display = "";
}

/**
 * ################################################ 
 * LOGIN PART
 * ################################################
 */
function reloadOnceOnly() {
	window.location.replace(window.location);
}

function login(type) {
	if (type == 'in') {
		var userName = document.getElementById('username').value;
		var password = document.getElementById('password').value;
		var rememberMe = 0;
		if (document.getElementById('zapamti_me').checked)
			rememberMe = 1;
			
		if (userName == "Username" || password == "Password")
			alert("Username or Password empty");
		else if (userName && trim(userName) && password && trim(password)) {
			showLoading();

			sendPost("proceedLogin/", "data=" + userName + "|" + password + "|"
					+ rememberMe, 'proceedLogin(');
		} else
			alert("Username or Password empty");
	} else {
		sendGet("proceedLogin/out", 'proceedLogin(');
	}
}

function proceedLogin(data) {
	var timer = 2000;
	fadeBox("flBox", timer); // Osvjezi (fadeout) aBoxOk nakon 2sec

	if (data.showDone) {
		floatWindow('<div id = "flBox"><div class = "ajaxBoxMsg" id="aboxOk"><img src = "img/small_ok.gif"><br/><br/>' + data['showDone'] + '</div></div>');
		setTimeout("reloadOnceOnly()", timer + 1000); 
	} else if (data.errors) {
		floatWindow('<div id = "flBox"><div class = "ajaxBoxMsg" id="aboxNo"><img src = "img/small_crit.gif"><br/><br/>' + data['errorMsg'] + '</div></div>');
	}
	hideLoading();
}

// Dinamicka zamijena polja
function passwordChangeType(type) {
	var typeLower = type.toLowerCase();
	var fieldP = document.getElementById(typeLower);
	// alert(fieldP);
	if (fieldP.value == type) {
		if (typeLower == "username")
			fieldP.type = "text";
		else
			fieldP.type = "password";

		fieldP.value = "";
	} else if (fieldP.value == "") {
		fieldP.type = "text";
		fieldP.value = type;
	}
}

/**
 * ################################################ VIDEO PART
 * ################################################
 */
function vidFavorites(idV, whatTo, nmbrFav) {
	showLoading();

	var stringB;

	if (whatTo == "add") {
		nmbrFav = parseInt(nmbrFav) + 1;
		sendGet('addVideoToFavorites/' + idV + '/1', 'addFdo(' + nmbrFav + ', ');
	} else if (whatTo == "rem") {
		nmbrFav = parseInt(nmbrFav) - 1;
		stringB = 'video - fav of ' + nmbrFav;
		sendGet('addVideoToFavorites/' + idV + '/0',
				'addFdo(\'' + stringB + '\', ');
	}
}

function addFdo(nmbrF, data) {
	if (data.showDone) {
		update(data['showDone'], "fvrButton");
		update(nmbrF, 'favNmbrA');
	} else {
		update(data['errors'], "fvrButton");
	}

	hideLoading();
}

function repVideo(id) {
	showLoading();

	sendGet('reportVideo/' + id, 'repDo(');
}

function repDo(data) {
	if (data.showDone)
		update(data['showDone'], "repButton");
	else
		update(data['errors'], "repButton");
	hideLoading();
}

/**
 * ################################################ 
 * FIELD VALIDATION
 * ################################################
 */
function globalValidate() {
	var i;
	var j;
	var errorPrint = ""; // Potrebno setovati na empty jer vraca undefined
							// kroz prvi prolaz u petlji
	var errors = 0;

	// Prodji kroz sve elemente u formi
	for (i = 0; i < document.formA.elements.length; i++) {
		// Uzmi elemente u formi i podijeli ih u niz razbijajuci ih na mjestima
		// sa "_" (uzmi req element)
		var tmpName = document.formA.elements[i].name.split("_");
		var tmpFullName = "";

		// Spoji sve elemente koji nisu req (req je 0 element, zato krece petlja
		// od 1)
		for (j = 1; j < tmpName.length; j++)
			tmpFullName += tmpName[j] + " ";

		// Ako se radi o req polju, dodaj da je to polje obavezno u listu
		if (tmpName[0] == "req") {
			// Ispitaj dali su polja prazna (ukljucujuci i nakucane spaceove)
			if ((!document.formA.elements[i].value) || (!trim(document.formA.elements[i].value))) {
				errorPrint += "*<b>" + initialCap(tmpFullName) + "</b> is required.<br/>";
				errors++;
			}
		}
	}

	// Definisi error message box
	var errorMsg = document.getElementById("errorMessageBox");
	if (errors != 0) {
		errorMsg.style.display = "block";
		errorMsg.innerHTML = errorPrint;
	} else {
		errorMsg.style.display = "none";
		document.formA.submit();
	}
}

// Funkcija za Capitalize (nestolaa => Nestolaa) - pomocna funkcija za
// globalValidate
function initialCap(str) {
	var tmpVar = str.substr(0, 1).toUpperCase() + str.substr(1);

	return tmpVar;
}


/**
*	#############################################
*	#				UPLOAD PHOTOS				#
*	#############################################
*/
var count = 0;
var flag = 0;
var newNum = 0;

function addField(num)
{
    count++;
	/**
	*	Ako nije postavljen flag postavi novi num
	*	Flag se postavlja radi toga sto se samo jednom mora ucitati vrijednost
	*	num-a. Kako se funkcija addField poziva svaki put kada se
	*	klikne link za kreiranje nove forme, da nema flaga, svaki put bi se setovao
	*	newNum, tako da broja ne bi radio ono to treba.
	*/
	if(flag == 0) {
		newNum = num;
	}
	flag = 1;	//Setuj flag
	
	addHtml = '<div class = "galleryUpFormBck">Photo: <input onChange="typeCheck(this)" type="file" name="file['+ count +']" id="file['+ count +']" size = "42"/> <a href = "javascript:void(0)" onclick="updatePhotosNum(\'remP\', ' + null + '); this.parentNode.parentNode.removeChild(this.parentNode);"><img src = "img/rem_form.png" border="0"/></a></div>';

	if(newNum > 0) {
		addElement('displayFormUp','div', addHtml, {id:"uploadPhotoDiv"});
		newNum = newNum - 1;
		updatePhotosNum("addP", newNum); 
	} else
		alert("You reached photo limit per gallery.");
}

function updatePhotosNum(type, numP)
{
	if(type == "addP") {
		document.getElementById("remGal").innerHTML = numP;
	}else if(type == "remP"){
		var numK = newNum + 1;
		newNum = numK;
		document.getElementById("remGal").innerHTML = numK;
	}
}

function addElement(inEl, elTag, inHtml, otherD)
{
	parentEl = document.getElementById(inEl);
	newEl = document.createElement(elTag);

	for (index in otherD)
		newEl.setAttribute(index, otherD[index]);
		
	newEl.innerHTML = inHtml;
	parentEl.appendChild(newEl);
}

function submitPhotos()
{
	showLoading();
	var visina = document.body.scrollHeight + "px";
	coverArea();
	document.uploadPhoto.submit.value = "Uploading photos... Please wait";
}

//Get divs by its class name
function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

