//
// Javascript library for locationblocks
//
//
// This script file contains all required scripts for the locationblocks system
// 


//
// lbHtmlRowhighlight adds -over to the current classname of the row if highLight is true, and removes it when false
//
function lbHtmlRowHighlight(tableRow, highLight) {
	if (highLight) {
		if(tableRow.className.search("-over") == -1) { // only add once
			tableRow.className = tableRow.className.concat('-over');
//			window.status = tableRow.className;
		}
	} else {
		tableRow.className= tableRow.className.replace('-over', '');
	}

}


/**
 *  A simple function that sets two select boxes (drop downs) dependent on each other
 *  Using the "class" as a filter on the option: first list has an option with value=1 use class="sub_1" for elements in second to match it.
 *   
 * 
 * @param parent
 * @param child
 * @return
 */
function lbHtmlCascadeSelect(parentname, childname){
	
	var parent = $(parentname);
	var child = $(childname);
	
	var childOptions = child.find('[parentid]'); // all with parentid
	child.data('options',childOptions);

	parent.change(function(){
		childOptions.remove(); // remove all entries
		child.append(child.data('options').filter('[parentid=' + this.value + "]")).change();
		
		if($(childname+' option').length > 0) {
			child.attr("disabled","");
		} else {
			child.attr("disabled","disabled");
		}
		
	})

	childOptions.not('not([parentid]), [parentid=' + parent.val()+"]").remove();
	// set child disabled if no child elements for current selected value
	if($(childname+' option').length > 0) {
		child.attr("disabled","");
	} else {
		child.attr("disabled","disabled");
	}
	
}






//
// lbHtmlJumpTo sets an URL in the current window
//
function lbHtmlJumpTo(theUrl) {
	document.location.href = theUrl;
}



/**
 * Get a unique ID
 * 
 * @return string
 */
function lbGetUID() {
  var dt = new Date().getMilliseconds();
  var num = Math.random();
  var rnd = Math.round(num*100000);
  
  return "uid"+dt+rnd;
}



/**
 * lbProcessAjaxRequest is a client side function that process LBAjaxResponse classes 
 * 
 * @param data JSON formatted data to process
 * 
 */
function lbProcessAjaxResponse(data) {

//	var xuid = lbGetUID();
//	$('#lbajaxmessages').append( "<div id=\""+xuid+"\" class=\"ui-content "+style+" ui-corner-all\" style=\"padding:5px; margin:0; margin-bottom:3px;\">" + "called ajax response"  + "</div>" );
//	$('#' + xuid).show('highlight', 200).delay(2000).hide('highlight', 200);
	
	/* handle messages if present */
	if(data.message) {
		var uid = lbGetUID();
		
		var style = "ui-state-highlight";
		
		if(data.message.type == "error") { // other style on error messages
			style = "ui-state-error";
		}
		
		$('#lbajaxmessages').append( "<div id=\""+uid+"\" class=\"ui-content "+style+" ui-corner-all\" style=\"padding:5px; margin:0; margin-bottom:3px;\">" + data.message.message  + "</div>" );
		$('#' + uid).show('highlight', 200).delay(2000).hide('highlight', 200);
	}

	if(data.debug) { 
		lbAjaxDebugMessage( data.debug.message  );
	}

	
	/* Present "modal" message to get absolute attention from user */
	if(data.modal) {
		$.fancybox({
			'hideOnOverlayClick':true, 'overlayShow':true, 'showCloseButton':true, padding:20, 'content':data.modal.message
		});
	}

	
	
	/* parse all load items and perform the loads */
	if(data.load) {
		$.each(data.load, function(i, item) {
            	if(item.url) {
            		$('#' + item.container).load(item.url);
            	} else { // empty container
            		$('#' + item.container).empty();
            	}
		});
	}
	
	
	/* parse all html updates and set */
	if(data.html) {
		$.each(data.html, function(i, item) {
            	$('#' + item.id).html(item.html);
            
		});
	}

	
	/* parse all appends and set */
	if(data.append) {
		$.each(data.append, function(i, item) {
            	$('#' + item.id).append(item.html);
		});
	}

	
	
	/* parse all val updates and set */
	if(data.val) {
		$.each(data.val, function(i, item) {
            	$('#' + item.id).val(item.val);
            
		});
	}
	
	
	/* parse all javascript items and perform the loads */
	if(data.javascript) {
			$.each(data.javascript, function(i, item) {
					eval(item.javascript);
			});
	}
	
}

function lbAjaxDebugMessage(msg) {
	$('#lbajaxdebugmessages').prepend( "<pre>" + msg  + "</pre><hr>" );

}
 
 
/**
 * perform an ajax request and process the resulting ajaxResponse object.
 * 
 * It will execute an AJAX call using input as the basis for the data.
 * It will append _val with .val() and _text with .text() in addition to all attributes for thisin.
 * 
 * @param thisin the object representing the change (usually this)
 * @param json input arguments
 * 
 */ 
function lbAjaxRequest(thisin, input)  {

	input["_val"] = $(thisin).val();
	input["_text"] = $(thisin).text();
	var attrs = thisin.attributes;
	var l = attrs.length;

	for (var i=0;i<l; i++){
	    var attr = attrs.item(i);
	    input[attr.nodeName] = attr.nodeValue;
	}	
	
	$.ajax({ type: "POST", dataType: "json", url:"?", data: input, 
			success: function(data){ lbProcessAjaxResponse(data) },
			error: function(xmlrex, textmsg){ 
				lbAjaxDebugMessage('Ajax POST failed inside lbAjaxRequest: '+textmsg);
				}
		
		});
}
 
 /**
  * perform an ajax request with a simple GET method
  * @param string url to be executed. ($navigator->getURL() can be used)
  * 
  */ 
 function lbAjaxRequestGet(url, indata)  {
 	$.ajax({ type: "GET", dataType: "json", url:url, data:indata, 
 			success: function(data){ lbProcessAjaxResponse(data) },
 			error: function(xmlrex, textmsg){ 
 				lbAjaxDebugMessage('Ajax GET failed inside lbAjaxRequestGet: '+textmsg);
 				}
 		
 		});
 } 
  
  
/**
 *
 * This function is used to update the progress page defined in core/jquery.php
 * 
 * 
 * @param jobid
 * @param lastmessage
 * @return void
 */  

  function lbAjaxSchedulerProgress(progressid, lastmessage) {
  	var data = { progressid:progressid, lastmessage:lastmessage};
  	
  	$.ajax({dataType: 'json', url: 'progressupdate.php', data: data, success: function(data) {
 		
  		if(! data) {
  			/* cleanup some stuff */
			$(".progressmessages[progressid='"+progressid+"']").html('');
  			$(".progressbar[progressid='"+progressid+"']").progressbar( "option", "value", 0 );
  			$(".progresstasktitle[progressid='"+progressid+"']").html("&nbsp;");

  			/* retry */
  			setTimeout('lbAjaxSchedulerProgress('+progressid+','+lastmessage+')', 100);

  			return;
  		}
  		
  		var lastmsg = data.lastmessage;
  		
  		if(data.messages) {
  			var num = data.messages.length;
  			/* display messages */
  			for (var i=lastmsg;i<num;i++)	{
  				$(".progressmessages[progressid='"+progressid+"']").append(data.messages[i]+'<br>');
  			}
  			
  			/* scroll to bottom */
  			$(".progressmessages[progressid='"+progressid+"']").each(function() { this.scrollTop = this.scrollHeight; });
  			lastmsg = i;
  		}

  		if(data.progress >=0) {
  			$(".progressbar[progressid='"+progressid+"']").progressbar( "option", "value", parseFloat(data.progress) );
  			$(".progressbartext[progressid='"+progressid+"']").html( parseFloat(data.progress) + " %" );
  		}
  		if(data.taskname) {
  			$(".progresstasktitle[progressid='"+progressid+"']").html(data.taskname );
  		}
  		
  		/* repeat ourselves if not completed */
  		if( data.completed == false) {
  			setTimeout('lbAjaxSchedulerProgress('+progressid+','+lastmsg+')', 100); 
  		} else { /* completed - activate continue button */
  			
  			$(".progressbarbutton[progressid='"+progressid+"']").html(data.completelabel);
  			$(".progressbarbutton[progressid='"+progressid+"']").bind('click', function() { lbHtmlJumpTo(data.completeurl) } );
  			$(".progressbarbutton[progressid='"+progressid+"']").toggle(true);
  			
  		}
  		
  	}, error: function() { 
  		lbAjaxDebugMessage("lbAjaxSchedulerProgress failure for progressid: " + progressid); 
  	}  });	
  }
  
