// Loading 
loading = {

	tpl: '<div id="mkcms_loading">Loading...</div>',

	show: function ()
	{
		$(this.tpl).prependTo('body');
	},

	hide: function ()
	{
		$('#mkcms_loading').remove();
	}
};

// Ajax settings START
$.ajaxSetup({
	dataType:'json', 
	beforeSend: function() { 
		loading.show(); 
	}, 
	complete: function() { 
		loading.hide(); 
	}
});

// Formatira string za normalan prikaz u browseru
function seoString(str)
{
	if (str)
	{
		var org = [" ", "Č", "č", "Ć", "ć", "Đ", "đ", "Š", "š", "Ž", "ž"];
		var rep = ["_", "C", "c", "C", "c", "D", "d", "S", "s", "Z", "z"];
		
		for (i in org)
		{
			var t = new RegExp(org[i], "g");
			str = str.replace(t, rep[i]);
		}
		
		// Ostavlja samo slova, brojeve, - i _
		str = str.replace(/[^a-zA-Z0-9\-_]/g, "");
		
		// Brise visestruko pojavljivanje crtica zaredom
		str = str.replace(/[-]+/g, "-");
		str = str.replace(/[_]+/g, "_");
		
		// Prebacuje sve u mala slova
		str = str.toLowerCase();
	}
	
	return str;
}

/* Brise html tagove iz texta */
function stripTags(str) 
{
    return str.replace(/<\/?[^>]+>/gi, '');
}

/* Briše nevidljive znakove sa pocetka i kraja stringa */
function trim(str) 
{
	chars = "\\s";
	str = str.replace(new RegExp("^[" + chars + "]+", "g"), ""); // Left
	return str.replace(new RegExp("[" + chars + "]+$", "g"), ""); // Right
}

/*
	Manipulacija hash dijelom urla
	
	Funcije:
		* getAndRemove(what[, hash]) - selektuje varijablu (key=value), vraca kao array i brise iz hasha
			+ what - array sa keys varijabli koje treba selektovani
			+ [hash] - hash iz kojeg treba selektovati (ako se ne navede, uzima se hash trenutne lokacije)
*/

urlHash = {
	
	/* Selektuje varijable iz hasha i brise ih nakon toga */
	getAndRemove: function(what, hash)
	{
		var toReturn = '';
		var myArr = new Array();
		
		// Ako hash nije naveden postavlja trenutni
		if (!hash)
			hash = window.location.hash;
		
		// Ako hash postoji nastavlja
		if (hash)
		{
			// Brise "#" sa pocetka
			hash = hash.replace(/^#/,"");
			
			splitOne = hash.split("&"); // Dijeli na varijabla=vrijednost
			
			for (i in splitOne)
			{
				splitTwo = splitOne[i].split("=");	
				
				// Provjerava da li se trenutni key trazi
				if (urlHash.in_array(splitTwo[0], what))
				{
					myArr[splitTwo[0]] = unescape(splitTwo[1]); // Upisuje u array koji ce vratiti korisniku;					
					delete splitOne[i];
				}
			}
					
			// Postavlja novi hash (ostatak)
			var newHashArr = [];
			var newHashC = 0;
			for (i in splitOne)
				if (splitOne[i])
					newHashArr[newHashC++] = splitOne[i];					
			window.location.hash = "#"+newHashArr.join("&");
			
			// Vraca array korisniku
			return myArr;
		}
		
		return {};
	},
	
	/* Provjerava da li se vrijednost nalazi u arrayu */
	in_array: function (val, array) 
	{
		for (i in array)
			if (array[i] == val)
				return true;
				
		return false;
    }
};

function copyPoljeForUrlTag(polje1, polje2, text)
{
	var seoNaslov = seoString($(polje1).val());
	var urlTag = $(polje2).val();	
	var upisi = false;
			
	if (urlTag == '')
	{
		upisi = true;
	}
	else if ($(polje2).val() != seoNaslov && confirm(text))
	{
		upisi = true;
	}
				
	if (upisi == true)
	{
		$(polje2).val(seoNaslov);
	}
}

function serialize (mixed_value) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}
function unserialize (data) {
    // http://kevin.vanzonneveld.net
    // +     original by: Arpad Ray (mailto:arpad@php.net)
    // +     improved by: Pedro Tainha (http://www.pedrotainha.com)
    // +     bugfixed by: dptr1988
    // +      revised by: d3x
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +        input by: Brett Zamir (http://brett-zamir.me)
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: Chris
    // +     improved by: James
    // %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %            note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *       returns 1: ['Kevin', 'van', 'Zonneveld']
    // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
    // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
 
    var error = function (type, msg, filename, line){throw new this.window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;
 
        buf = [];
        for (var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;
 
        if (!offset) {offset = 0;}
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();
 
        var dataoffset = offset + 2;
        var typeconvert = new Function('x', 'return x');
 
        switch (dtype){
            case 'i':
                typeconvert = function (x) {return parseInt(x, 10);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'b':
                typeconvert = function (x) {return parseInt(x, 10) !== 0;};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'd':
                typeconvert = function (x) {return parseFloat(x);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'n':
                readdata = null;
            break;
            case 's':
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;
 
                readData = read_chrs(data, dataoffset+1, parseInt(stringlength, 10));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if (chrs != parseInt(stringlength, 10) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }
            break;
            case 'a':
                readdata = {};
 
                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;
 
                for (var i = 0; i < parseInt(keys, 10); i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;
 
                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;
 
                    readdata[key] = value;
                }
 
                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    
    return _unserialize((data+''), 0)[2];
};

function parse_str (str, array){
    // http://kevin.vanzonneveld.net
    // +   original by: Cagri Ekin
    // +   improved by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   reimplemented by: stag019
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: stag019
    // -    depends on: urldecode
    // %        note 1: When no argument is specified, will put variables in global scope.
    // *     example 1: var arr = {};
    // *     example 1: parse_str('first=foo&second=bar', arr);
    // *     results 1: arr == { first: 'foo', second: 'bar' }
    // *     example 2: var arr = {};
    // *     example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
    // *     results 2: arr == { str_a: "Jack and Jill didn't see the well." }
 
    var glue1 = '=', glue2 = '&', array2 = String(str).split(glue2),
    i, j, chr, tmp, key, value, bracket, keys, evalStr, that = this,
    fixStr = function (str) {
        return urldecode(str).replace(/([\\"'])/g, '\\$1').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
    };
 
    if (!array) {
        array = this.window;
    }
 
    for (i = 0; i < array2.length; i++) {
        tmp = array2[i].split(glue1);
        if (tmp.length < 2) {
            tmp = [tmp, ''];
        }
        key   = fixStr(tmp[0]);
        value = fixStr(tmp[1]);
        while (key.charAt(0) === ' ') {
            key = key.substr(1);
        }
        if (key.indexOf('\0') !== -1) {
            key = key.substr(0, key.indexOf('\0'));
        }
        if (key && key.charAt(0) !== '[') {
            keys    = [];
            bracket = 0;
            for (j = 0; j < key.length; j++) {
                if (key.charAt(j) === '[' && !bracket) {
                    bracket = j + 1;
                }
                else if (key.charAt(j) === ']') {
                    if (bracket) {
                        if (!keys.length) {
                            keys.push(key.substr(0, bracket - 1));
                        }
                        keys.push(key.substr(bracket, j - bracket));
                        bracket = 0;
                        if (key.charAt(j + 1) !== '[') {
                            break;
                        }
                    }
                }
            }
            if (!keys.length) {
                keys = [key];
            }
            for (j = 0; j < keys[0].length; j++) {
                chr = keys[0].charAt(j);
                if (chr === ' ' || chr === '.' || chr === '[') {
                    keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
                }
                if (chr === '[') {
                    break;
                }
            }
            evalStr = 'array';
            for (j = 0; j < keys.length; j++) {
                key = keys[j];
                if ((key !== '' && key !== ' ') || j === 0) {
                    key = "'" + key + "'";
                }
                else {
                    key = eval(evalStr + '.push([]);') - 1;
                }
                evalStr += '[' + key + ']';
                if (j !== keys.length - 1 && eval('typeof ' + evalStr) === 'undefined') {
                    eval(evalStr + ' = [];');
                }
            }
            evalStr += " = '" + value + "';\n";
            eval(evalStr);
        }
    }
}

// POLL
$(function() {
	$('form[name="poll"]:first').ajaxForm({
		"beforeSubmit":function() {
			if (!$('form[name="poll"] input[name="odgovor_id"]:checked').length)
			{
				alert("Izaberite odgovor!");
				return false;
			}
		},
		"success":function(data) {
			var text;
			
			if (data.showDone)
			{
				var relLink = $('form[name="poll"] .rezultati_link').attr('href');
				window.location = relLink;
			}
			else if (data.errors)
			{
				alert(data.errors.text);
			}
		}
	});
	
	$('form[name="poll"] .submit').click(function(event) {
		$('form[name="poll"]:first').submit();
		event.preventDefault();
	});
});


function showPlayer(elSel, flv, img, autoPlay)
{
	html = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="320" height="240" id="FlashID" title="Media Player">';
    html += '<param name="movie" value="../mediaplayer/player.swf" />';
    html += '<param name="quality" value="high" />';
    html += '<param name="wmode" value="opaque" />';
    html += '<param name="swfversion" value="9.0.45.0" />';
    html += '<!-- This param tag prompts users with Flash Player 6.0 r65 and higher to download the latest version of Flash Player. Delete it if you don’t want users to see the prompt. -->';
    html += '<param name="expressinstall" value="Scripts/expressInstall.swf" />';
    html += '<!-- Next object tag is for non-IE browsers. So hide it from IE using IECC. -->';
    html += '<!--[if !IE]>-->';
    html += '<object type="application/x-shockwave-flash" data="../mediaplayer/player.swf" width="320" height="240">';
    html += '<!--<![endif]-->';
    html += '<param name="quality" value="high" />';
    html += '<param name="wmode" value="opaque" />';
    html += '<param name="swfversion" value="9.0.45.0" />';
    html += '<param name="expressinstall" value="Scripts/expressInstall.swf" />';
    html += '<param name="flashvars" value="file='+flv+'&image='+img+'&autostart='+autoPlay+'" />';
    html += '<!-- The browser displays the following alternative content for users with Flash Player 6.0 and older. -->';
    html += '<div>';
    html += '<h4>Content on this page requires a newer version of Adobe Flash Player.</h4>';
    html += '<p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" width="112" height="33" /></a></p>';
    html += '</div>';
    html += '<!--[if !IE]>-->';
    html += '</object>';
    html += '<!--<![endif]-->';
    html += '</object>';
	
	$(elSel).html(html);
	
	return false;
}

/*
	Pusti muziku
*/
pusti_muziku = {
	"show":function() {
		$.get('../pusti_muziku/show/', {}, function(data) {
			$('body').prepend(data);
			pusti_muziku.positionDialog();
			pusti_muziku.loadAjaxForm();
			pusti_muziku.loadPlayer();
		}, 'html');
		return false;
	},
	
	"loadPlayer":function() {
		showPlayer('#pusti_muziku .player', '../uploads/pusti_muziku/forspan.flv', '../uploads/pusti_muziku/logo.jpg', true);
	},
	
	"loadAjaxForm": function() {
		$('#pusti_muziku_form').ajaxForm({
			"beforeSubmit": function() {
				if (!$('#pusti_muziku input[name="opcija_id"]:checked').length)
				{
					alert('Morate izabrati jednu od opcija!');
					return false;
				}
			},
			"success":function(data) {				
				if (data.showDone)
				{
					alert(data.showDone.text);
				}
				else if (data.errors)
				{
					alert(data.errors.text);
				}
			}
		});
		$('#pusti_muziku a.submit').click(function(el) {
			$('#pusti_muziku_form').submit();
			el.preventDefault();
		});
	},
	
	"positionDialog":function() {
		
		var dHeight = $('#pusti_muziku').height();
		var dWidth = $('#pusti_muziku').width();
		var windowHeight = $(window).height();
		var windowWidth = $(window).width();
		var scrolledTop = $(window).scrollTop();
		var scrolledLeft = $(window).scrollLeft();
		
		var top = (windowHeight-dHeight)/2 + scrolledTop;
		var left = (windowWidth-dWidth)/2 + scrolledLeft;
		
		$('#pusti_muziku').css('top', top).css('left', left);
		
		pusti_muziku.bindClose();
	},
	
	"bindClose":function() {
		$('#pusti_muziku a.close').click(function(ev) {
			pusti_muziku.close();
			ev.preventDefault();
		});
	},
	
	"close":function() {
		$('#pusti_muziku').remove();
	}
};