
//alert($(document).find('form[rel!=ajaxoff]').length);

/**
 * @author Tato
 */
/**
 * Ajax History/Back Functions
 */
//var lastLocation = '';

/**
 * function for quick reloading of parts of pages via ajax
 * @param URL what to load
 * @param ID id attribute of DIV where to load
 */
 
 /*
function onAjaxLoadSuccess(a)
{
	initHistory(1);
	initHistory2(1);
	initForms();
	initRpcLinks();
} 

 function doReload(url, divId)
 {
 	unique = '#i007';
 
 	if ($('#' + divId).children(unique).length > 0){
	 	jQuery(unique).load(url, null , function() {onAjaxLoadSuccess()}).attr('style' , 'display: block');
	 	jQuery('#' + divId).attr('style' , 'display: block');
 	} else { 	
	 	jQuery('#' + divId).load(url, null , function() {onAjaxLoadSuccess()}).attr('style' , 'display: block');
 	} 	
 }
 
function pageload(hash){
    var xhrDivs = jQuery('div.innerXhr');   //-> s obzirom da smo maknuli innerxhr to vise ne radi :P
    if (hash) {
        // emptying ajax divs not used currently
        xhrDivs.each(function(){
            var prevDivId = jQuery(this).prev().attr('id');
            if (undefined != prevDivId) {
                if (-1 == hash.indexOf(prevDivId)) {
                    jQuery(this).prev().show().end().empty().remove();
                }
            }
        });
        
        
        // get object with target/file pairs
        locations = getLoadFiles(hash);
        
        for (var i = 0; i < locations.length; i++) {
            //var target = jQuery('#' + locations.targets[i]);
            
            // check for and create inside "ajax" div
           /* if (jQuery(target).next().attr('class') != 'innerXhr') {
                var newXhrDiv = jQuery('<div class="innerXhr" id="' + locations.targets[i] + 'InnerXhr"></div>');
                jQuery(target).after(newXhrDiv).remove();
            }
            */

            // checking to see, if file for loading has already been loaded before
     //       if (-1 == lastLocation.indexOf(locations.targets[i] + '=' + locations.files[i])) {
                //jQuery('#' + locations.targets[i] + 'InnerXhr').load(locations.files[i], null, function() { onAjaxLoadSuccess()});


       //         doReload(locations.files[i], locations.targets[i]);

  /*          }
        }
    }
    else {
        // start page
        // empty all inner ajax enabled divs, show targets
        xhrDivs.each(function(){
            $(this).prev().show().end().empty().remove();
        });

    }
    lastLocation = '';

}



function getLoadFiles(hash){
    if (-1 != hash.indexOf('#')) {
        // erase everything before and including #
        hash = hash.substr(hash.indexOf('#') + 1);
    }
    
    var files = new Array;
    var targets = new Array;
    var resources = new Object;
    
    var hashes = hash.split(',');
    var hashesCount = hashes.length;
    var i = 0;
    
    for (i; i < hashesCount; i++) {
        splitPlace = hashes[i].indexOf('=');
        targets[i] = hashes[i].substr(0, splitPlace);
        files[i] = hashes[i].substr(splitPlace + 1);
    }
    
    resources['length'] = hashesCount;
    resources['files'] = files;
    resources['targets'] = targets;
    
    return resources;
}

function stripTags(html)
{
	return html.replace(/(<([^>]+)>)/ig,"");
}
function onAjaxError(XHRObject, error, exception)
{
	alert(stripTags(XHRObject.responseText));
}

function onAjaxSuccess(data, onsucc)
{
	if (onsucc != -1){
		eval (onsucc);	
	} else {
		flashMessage(text)
	}
}
function initRpcLinks()
{
	selector = 'a[rpc]';
	jQuery(selector).unbind('click').click(function() 
	{
		onsucc = jQuery(this).attr('onsucc') || -1;
		rpcClick(jQuery(this).attr('rpc'), onsucc);
		return false;
	});
	return jQuery(selector);
}

function rpcClick(rpc, onsucc) {

	jQuery.ajax({ 	
		dataType: "json",
		type: "POST",
		url: rpc,
		success: function(data){onAjaxSuccess(data, onsucc)},
		error: function(XHRObject, error, exception){onAjaxError(XHRObject, error, exception)}
	})
}
/*
function initHistory(dontInitHistory){
	// setting callback function for History plugin
	//Ako nije predan parametar onda napravi inicijalizaciju, inace nemoj
    if(dontInitHistory==null) {
	    //jQuery.historyInit(pageload); ->zove se u history 2 pa tu vise netreba
	}

    selector = "a[@rel='history']";
    // set onlick event for ajaxified buttons
    jQuery(selector).click(function(){

        var hash = this.href;

        hash = hash.substr(hash.indexOf('?') + 1);
        // current URL, needed for extracing the target=file pairs
        var locationHref = window.location.href;
        locationHref = (-1 != locationHref.indexOf('#')) ? locationHref.substr(locationHref.indexOf('#') + 1) : '';
        lastLocation = locationHref;
        var target = this.rev;
        // this hash we'll load
        var loadHash = hash;

        if (locationHref) {
            var replacedFileTarget = false;
            loadHash = '';
            
            // get object with target/file pairs
            locations = getLoadFiles(locationHref);
            for (var i = 0; i < locations.length; i++) {
            
                // is this target equal to any already in URL?
                if (target == locations.targets[i]) {
                    // zamijeni files[i] sa hash.file (substraj)
                    locations.files[i] = hash.substr(hash.indexOf('=') + 1);
                    replacedFileTarget = true;
                }
                
                // building hash to load
                if (i > 0) {
                    loadHash += ',' + locations.targets[i] + '=' + locations.files[i];
                }
                else {
                    loadHash += locations.targets[i] + '=' + locations.files[i];
                }
            }
            
            if (!replacedFileTarget) {

                loadHash += ',' + hash;
            }
        }
        hash = loadHash;
        // moves to a new page. 
        // pageload is called at once.
        

       	jQuery.historyLoad(hash);
		setInterval("initHistory(1)", 100); //Pauza od 100 ms prije poziva funkcije initHistory(1)
		//Ovdje je potreban delay neki kolki je inace u history-u
		//History i cijeli ajax radi na principu da se setira neki url
		//A history objekt svaki 100 ms cekira da li je doslo do promjene i onda izvodi cuda :)
        return false;
    }).attr("rel","");
    
    // maknut parametar koji se gleda za ajax kako se nebi na iste linkove zakacio dva puta isti event
}
*/
/**
 * AJAX FORMS
 */
/**
 * binds ajax submitting to all forms OR the one just reloaded
 * it finds forms in DIV elements with SRC attribute
 * 
 *
 * @return  {void}
 */
/*
function initForms()
{
	jQuery('div[@src]').each(function(){bindForm(this)});	
}

/**
 * Binds ajax submitting to a form
 * 
 * @param {DOM Object} elem - DIV which contains form
 */
 /*
function bindForm(elem)
{       
    var $thisDiv = jQuery(elem);
    var thisId = jQuery($thisDiv).attr('id');   
    var target = jQuery($thisDiv).attr('src'); //U koji div id ce se se izredndati response




    $thisDiv.find('form[ajax!=off]').append(initFormLoader()).ajaxForm(formOptions(thisId, target));
}*/

/**
 * Creates Options object for initForms()
 * Options object is used by ajaxForm()
 *
 * @param   {string} id - ID of DIV where to refresh content on successful submit
 * @param   {string} action - alternative ACTION
 * @return  {void}
 */
 /*
function formOptions(id, action)
{
    function ltrim(str, chars)
    {
		chars = chars || "\\s";
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }
    action = '/' + ltrim(action, '/');
    
    var options = {
    	method:'POST',
        target: '#' + id,
        url: action,
        beforeSubmit: preSubmit, // pre-submit callback
        success: postSubmit // post-submit callback
    };
    return options;
}*/

/**
 * pre-submit callback
 * 
 * shows loader
 */
/*preSubmit = function (formData, jqForm, options)
{  
	
	//jQuery(jqForm).find('.formLoader').show();
	
	$(jqForm).find('input, textarea, select').attr("disabled", true);
	$(jqForm).attr('class', 'disabled');
}*/

/**
 * post-submit callback
 * 
 * hides loader
 * ds Ajax form submitting for just reloaded form (this)
 */
 /*
postSubmit = function (responseText, statusText)
{
	//jQuery('.formLoader').hide();
    onAjaxLoadSuccess();
}

/**
 *  Dialog (popup box)
 */
 /*
function initDialogs(){
    jQuery.historyInit(pageload);
    jQuery("a[@rel='history']").click(function(){
        var hash = this.href;
        var target = this.target;
        showDialog(target);
        hash = hash.replace(/^.*#/, '');
        jQuery.historyLoad(hash, target);
        return false;
    });
}

function hideDialog(dialogId){
    jQuery('#' + dialogId).css('display', 'none');
    jQuery.historyLoad('', dialogId);
    return false;
}

function showDialog(dialogId){

    jQuery('#' + dialogId).css('display', 'block');
    return false;
}
*/

/**
 * GENERIC LOADER BOXES
 */
// TODO: check for elements used in current page, and accordingly initialize loaders
/*function initLoaders()
{
    initFormLoader();
}*/
/*
function initFormLoader()
{
    return jQuery('<div class="formLoader">Pričekajte trenutak...</div>');
}*/

jQuery.fn.extend({
 getUrlParam :  function(strParamName){
	  strParamName = escape(unescape(strParamName));
	  
	  var returnVal = new Array();
	  var qString = null;
	  
	  if ($(this).attr("nodeName")=="#document") {
	  	//document-handler
		
		if (window.location.search.search(strParamName) > -1 ){
			
			qString = window.location.search.substr(1,window.location.search.length).split("&");
		}
			
	  } else if ($(this).attr("src")!="undefined") {
	  	
	  	var strHref = $(this).attr("src")
	  	if ( strHref.indexOf("?") > -1 ){
	    	var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	  		qString = strQueryString.split("&");
	  	}
	  } else if ($(this).attr("href")!="undefined") {
	  	
	  	var strHref = $(this).attr("href")
	  	if ( strHref.indexOf("?") > -1 ){
	    	var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	  		qString = strQueryString.split("&");
	  	}
	  } else {
	  	return null;
	  }
	  	
	  
	  if (qString==null) return null;
	  
	  
	  for (var i=0;i<qString.length; i++){
			if (escape(unescape(qString[i].split("=")[0])) == strParamName){
				returnVal.push(qString[i].split("=")[1]);
			}
			
	  }
	  
	  
	  if (returnVal.length==0) return null;
	  else if (returnVal.length==1) return returnVal[0];
	  else return returnVal;
	}
});

flashMessage = function (data)
{
	text = '';
    if (typeof data == 'string'){
		text = data;
	}else if(!data.info){
		$.each(data, function(i)
		{
			text += data[i].text + "<br />";
		})
	} else {
		allMessages = data.info.messages;
		$.each(allMessages, function(i)
		{
			text += allMessages[i].text + "<br />";
		})
	}
	
	speed=2000;
	jQuery('#flashmessage').html(text).fadeIn(speed, function(){jQuery('#flashmessage').fadeOut(speed)})
}
/*
function initHistory2(dontInitHistory){
    // setting callback function for History plugin
    //Ako nije predan parametar onda napravi inicijalizaciju, inace nemoj
    if(dontInitHistory==null) {
        jQuery.historyInit(pageload);
    }

    selector = "a[ajax]";
    // set onlick event for ajaxified buttons, but first unbind any click funcitons  
    jQuery(selector).unbind('click').click(function(){
        var hash = this.href;
        
        
        hash = $(this).attr('ajax');
        var isHistory = $(this).attr('history');
        var target = $(this).attr('blok');
        if(isHistory == 0)
        {
            doReload(hash, target);
            return false;
        }else{
	        // current URL, needed for extracing the target=file pairs
	        var locationHref = window.location.href;
	        locationHref = (-1 != locationHref.indexOf('#')) ? locationHref.substr(locationHref.indexOf('#') + 1) : '';
	        lastLocation = locationHref;
	        hash = target + '=' + hash;
	        // this hash we'll load
	        var loadHash = hash;
	
	        if (locationHref) {
	            var replacedFileTarget = false;
	            loadHash = '';
	            
	            // get object with target/file pairs
	            locations = getLoadFiles(locationHref);
	            for (var i = 0; i < locations.length; i++) {
	            
	                // is this target equal to any already in URL?
	                if (target == locations.targets[i]) {
	                    // zamijeni files[i] sa hash.file (substraj)
	                    locations.files[i] = hash.substr(hash.indexOf('=') + 1);
	                    replacedFileTarget = true;
	                }
	                
	                // building hash to load
	                if (i > 0) {
	                    loadHash += ',' + locations.targets[i] + '=' + locations.files[i];
	                }
	                else {
	                    loadHash += locations.targets[i] + '=' + locations.files[i];
	                }
	            }
	            
	            if (!replacedFileTarget) {
	
	                loadHash += ',' + hash;
	            }
	        }
	        hash = loadHash;
	        // moves to a new page. 
	        // pageload is called at once.
	        $.historyLoad(hash);
	        setTimeout("initHistory2(1)", 100); //Pauza od 100 ms prije poziva funkcije initHistory2(1)
	        //Ovdje je potreban delay neki kolki je inace u history-u
	        //History i cijeli ajax radi na principu da se setira neki url
	        //A history objekt svaki 100 ms cekira da li je doslo do promjene i onda izvodi cuda :)
	        return false;
	    }    
    })
}*/
/*
function confirmDelete(){
	return confirm('Jeste li sigurni?');
}
*/
