/**
 * 18.05.2009 - suwJKeepAlive trimite cereri spre adminAJAX.php
 * 16.05.2009 - suwJKeepAlive - foloseste ajax pentru a tine conexiunea activa
 * 			  - suwDontSubmitFormOnEnterKey - ignora tasta enter in cazul in care este apasata pe un element input field
 * 				din formular. Impiedica trimiterea accidentala a datelor din form. in caz de ENTER.
 * 23.08.2008 - functia confirm - jQuery simpleModal box in loc de confirm javascript!
 **/

/**
 * SuW Preview Image, set popupView div visible and insert Image into it
 * 
 * @param string imageName - image name to read
 * @param string path	- image path
 * @param string selName - selector Name to read the value
 **/
function previewImg(imageName,path,selName){	
	var obj=$("#popupView");

  //get value from selected element	
	if(imageName==null && typeof(selName)=='string')
		imageName=$("select#"+selName)[0].value;

	if(!imageName){
		obj.hide();
		return;
	}
	
	if(path)
		imageName=path+"/"+imageName;
	
	var imgURL='viewImg.php?max=300&img='+imageName;
	var spn='templates/admin/imgs/upload_file.gif';
	
	obj.css({'top':'5%','left':'20%'});
	obj.show();
	obj.html("<img src='"+spn+"'>");
	
	$.ajax({
		url: imgURL,
		dataType: 'html',
		async: false,
		error: function(){
			obj.html("<b>Error</b> loading image: "+imgURL);
		},
		success: function(){
				obj.find('img').attr('src',imgURL); 
		}
	});
}


//Redirect to location
function redir(loc){
	if(loc.substring(0, 4)=="http")
	 document.location=loc;
	else
	 document.location="?"+loc;
}



/*
 * Focus on an form element
 */
function autoFocus(fname,el){
	var p=document.forms[fname]
	p.elements[el].focus(true);
}

//-------------------------------------------------------[key input Numbers Only]
/**
 * USAGE: onKeyDown="return nrOnly(event)";
 * 9=tab 8,46=del,bkpsp
**/
function nrOnly(e){
	var key = (window.event ? window.event.keyCode : e.which);
	//alert(key);
	if( (key>=48 && key <=57) || (key>=96 && key<=105) || (key==8) || (key==46) || (key==9) || (key==190) || (key==110) )	
		return true;
	
	return false;
}


var pub=false;
//var delMsg << used in admin
/**
 * Redirectare stergere obiect.
 * Folosit in formulare, pentru a nu sterge accidental un obiect.
 *
 * 23.08.2008 - foloseste functia suw confirm in loc de cea clasica
 *
 */
function ask4Del(redirContent){
	if(arguments[1])
		var msg=arguments[1];
	else
		var msg=delMsg;
	
	confirm(msg,redirContent);
}



//open popup with image
var _W;
 function view1ON1(imgname){
 	file="imgPopup.php?image="+imgname;
	if(_W){ _W.close(); }
	_W=window.open(file,'w','width=100,height=100');
		_W.focus();
    	_W.moveTo(100,50);
 }



//functions for ordering
var suw_ord=0;

function suwOrd(id){
	var objName="ord_"+id;
	var obj=document.getElementById(objName);
	if(obj.value==''){
		suw_ord++;
		obj.value=suw_ord;
	}
}

function setOrd(obj){
  var nr=obj.value;
  
  if(parseInt(nr) == parseFloat(nr))
  	suw_ord=nr;
  else{
  	suw_ord=0;
  	obj.value="";
  	}
}


/**
 * Replace confirm with jQuery Modal CONFIRM
 * @param string message - message to show
 * @param function/string callback - function to call on yes. 
 * 								   - string - http address to redirect to. -
 * ex:
 *	//to redirect
 *		confirm('SuW Engine MODAL confirm text?','http://localhost');
 *
 *	//to call a function
 * 		confirm('SuW Engine MODAL confirm text?',function(){alert(123);});
 *
 *	//to be used as a simple message box without confirmation buttons
 *		confirm('SuW Engine MODAL confirm text?');	
 * 
 **/
function confirm(message, callback) {
	$('#confirm').modal({
		close:false, 
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer', 
		onShow: function (dialog) {
			dialog.data.find('.message').append(message);
			
			if(!callback)
				$("div .buttons").hide();
			else{
				$("div .buttons").show();
			// if the user clicks "yes"
				dialog.data.find('.yes').click(function () {
					switch(typeof(callback)){
						case "function":
							$.modal.close();
							callback.apply();
							return;
							break;
						case "string":
							redir(callback);
							break;	
					}
				// close the dialog
					$.modal.close();
				});
			}
		}
	});
}


/**
 * Enable TAB in textarea
 * Usage:
 * 	<textarea ... onkeypress="textareaTab(event);">
 */
// Set desired tab- defaults to four space softtab
var tab = "    ";
function textareaTab(evt) {
    var t = evt.target;
    var ss = t.selectionStart;
    var se = t.selectionEnd;

    // Tab key - insert tab expansion
    if (evt.keyCode == 9) {
        evt.preventDefault();
        
        // Special case of multi line selection
        if (ss != se && t.value.slice(ss,se).indexOf("\n") != -1) {
            // In case selection was not of entire lines (e.g. selection begins in the middle of a line)
            // we ought to tab at the beginning as well as at the start of every following line.
            var pre = t.value.slice(0,ss);
            var sel = t.value.slice(ss,se).replace(/\n/g,"\n"+tab);
            var post = t.value.slice(se,t.value.length);
            t.value = pre.concat(tab).concat(sel).concat(post);
            
            t.selectionStart = ss + tab.length;
            t.selectionEnd = se + tab.length;
        }
        
        // "Normal" case (no selection or selection on one line only)
        else {
            t.value = t.value.slice(0,ss).concat(tab).concat(t.value.slice(ss,t.value.length));
            if (ss == se) {
                t.selectionStart = t.selectionEnd = ss + tab.length;
            }
            else {
                t.selectionStart = ss + tab.length;
                t.selectionEnd = se + tab.length;
            }
        }
    }
    
    // Backspace key - delete preceding tab expansion, if exists
    else if (evt.keyCode==8 && t.value.slice(ss - 4,ss) == tab) {
        evt.preventDefault();
        
        t.value = t.value.slice(0,ss - 4).concat(t.value.slice(ss,t.value.length));
        t.selectionStart = t.selectionEnd = ss - tab.length;
    }
    
    // Delete key - delete following tab expansion, if exists
    else if (evt.keyCode==46 && t.value.slice(se,se + 4) == tab) {
        evt.preventDefault();
        
        t.value = t.value.slice(0,ss).concat(t.value.slice(ss + 4,t.value.length));
        t.selectionStart = t.selectionEnd = ss;
    }
    
    // Left/right arrow keys - move across the tab in one go
    else if (evt.keyCode == 37 && t.value.slice(ss - 4,ss) == tab) {
        evt.preventDefault();
        t.selectionStart = t.selectionEnd = ss - 4;
    }
    else if (evt.keyCode == 39 && t.value.slice(ss,ss + 4) == tab) {
        evt.preventDefault();
        t.selectionStart = t.selectionEnd = ss + 4;
    }
}

/**
 * Dropdown DOM element populator
 */
$.fn.addValues = function (jsonValues){
	if (typeof(jsonValues) == "object") {
		options = "<option></option>";
		for (a in jsonValues) 
			options += ("<option value='" + a + "'>" + jsonValues[a] + "</option>");
		
		$(this).html(options);
	}
}

/**
 * Request from url json data to populate dropdown element.
 * @param {Object} url
 */
$.fn.suwGetAJXImgList = function(url){
	var obj=this;
	$(obj).html("<option>...</option>");
	
	$.getJSON(url,function(data){
		$(obj).addValues(data);
	});
}

/**
 * Afiseaza text definint in jsTemplateView intr-un div definit,
 * in functie de elementele selectate dintr-un dropdown
 * Cheile din jsTemplateView trebuie sa fie exact id-urile elementului dropdown. 
 *
 * @param string divView - numele div-ului unde se afiseaza textul
 * @param array enDisElements - array cu numele elementelor ce de dezactiveaza/activeaza
 */
$.fn.suwDivView = function(divView,enDisElements){
	var obj = this;
	var divObj = $(divView);
	
	var doIT = function(){
		var selected = obj.val();
		divObj.html(jsTemplateView[selected]);
		
		if(!enDisElements)
			return;
		
		for (a in enDisElements) {
			element = $("[name=" + enDisElements[a] + "]");
			if ( selected.length>1 || parseInt(selected)>0 ) 
				element.attr("disabled","disabled");
			else 
				element.removeAttr("disabled");
		}
	}
	
	doIT();
	obj.change(function(){doIT();});
}

/**
 * Functie ptr tinerea conexiunii active
 * @param string suwEngineURL - http url
 */
 $.fn.suwJKeepAlive = function(suwEngineURL){
 	var obj=$(this);
	var time=60000;
	
	var readSuwDateTime = function(){
		obj.addClass("keepAliveMotion");
		$.ajax({
	   		type: "POST",
			cache: false,
			dataType: "html",
/*
 * 			error: function(){
				ajaxErrorMsg()
			},
*/
			url: suwEngineURL+"/adminAJAX.php",
	   		data: "suw=keepAlive",
	   		success: function(msg){
	     			obj.removeClass("keepAliveMotion").html(msg);
	   		}
		});
	};
	
	$.timer(time, function (timer) {
		readSuwDateTime();
		timer.reset(time);
   	});
 }

/**
 * Mesaj eroare AJAX 
 */
function ajaxErrorMsg(msg){
	mesaj = ((msg) ? msg : "Session closed!");
	alert(msg);
}

/**
 * Dezactiveaza tasta ENTER in cazul in care este detectata
 * Ex. la formulare - trimiterea accidentala a datelor. 
 */
$.fn.suwDontSubmitFormOnEnterKey=function(){
	
   if ($.browser.mozilla)
      return $(this).keypress(checkForEnter);
   else 
      return $(this).keydown(checkForEnter);
   
   function checkForEnter(event) {
      if (event.keyCode == 13) {
	  	event.stopPropagation();
	  	event.preventDefault();
	  	return false;
	  }
   };
}

/**
 * Returneaza numele fisierului
 * @param {string} path
 * @return {string}
 * @example basename("/images/loc/img.jpg") => img.jpg
 */
function basename(path) {
    return path.replace( /.*\//, "" );
}
/**
 * Returneaza calea
 * @param {string} path
 * @return {string}
 * @example dirname("/images/loc/img.jpg") => /images/loc
 */
function dirname(path) {
    return path.match( /.*\// );
}
