/**
 * Common Javascript
 *
 * @author	  Mustabasic Reuf
 * @copyright Copyright &copy; 2009, Mustabasic Reuf
 * $Id: common.js 1498 2011-12-21 23:06:21Z reuf $
 *
 */

/*
 * Empty function to use with the SetFB problem (use into the empty "onsuccess")
 */
function EmptyFunctionSetFB(){

 var url = '';

 new Ajax.Request(url,{
                    method: 'get',
                    onSuccess: function(transport) {
                    }

            });

}

/**
 * used for benchmarking javascript execution time
 */
var timed = {
	time: undefined,
	start: function () {
		d = new Date();
		this.time = d.getTime();
	},

	getDiff: function () {
		d = new Date();
		return d.getTime() - this.time;
	}
}

var msg ;
msg = document.createElement('div');
msg.id = 'fbc';
msg.className = "feed_back_div";

msg.onclick = function(e){
					Element.remove(this);
					msg.className = "feed_back_div";
					msg.innerHTML = "";

				}


function FeedBack(message){

	var tmp = "";
	var error = false;
	// new system, SetFB
	if (typeof message == "object" && message.responseText == undefined ){

		if(message['notice'] != undefined){
				tmp = message['notice'][0];
		}

		if(message['error'] != undefined){
				tmp = message['error'][0];
				error = true;
				msg.className += " feed_back_div_error";
		}

	//old system
	}else if (typeof message == "object" && message.responseText != ""){

        tmp = message.responseText + "<br />";

	}else if (typeof message == "string"){

        tmp = message + "<br />";
	}

	var el =  document.createElement('div');
	el.id = Math.random();
	el.innerHTML = tmp;

        // Set the delay of the appareance of the message
        if(tmp.length >= 40)
            var time_delay = 3;
        else
            var time_delay = 3;

 	msg.appendChild(el);

 	document.body.appendChild(msg);

	if(!error) {
			new Effect.SwitchOff(el, {delay : time_delay});

// 			new PeriodicalExecuter(function(pe){
// 					Element.remove(el)
// 					pe.stop();
// 				}, 13);
	}
}

/**
* Globalhandlers will take care about notification when a
* request is created and when is finished to inform user about
* what is going on
*/
var globalHandlers = {

	onException: function(request, exception) {
		Element.hide('progress');
		alert("Js Exception: " + exception );
	},

	onCreate: function(request, transport){

		if($('progress'))
			Element.show('progress');

	},

	onComplete: function(request, transport, json){

		if(Ajax.activeRequestCount == 0)
			Element.hide('progress');

		FeedBack(json);
	}
}

Ajax.Responders.register(globalHandlers);

/*************************************************/


/**
* Get the list of active users
*
*/
function GetActiveUsers(){

	var url = 'admin/ajax/ajax_admin.php?do=get_active_users';

		var ajax = new Ajax.Request(
			url,
			{
				method: 'get',
				onComplete: function(response) {

					$('active_users').style.display='block';

					var t = '';
					var obj = response.headerJSON.evalJSON(true);
					var arr = obj['data'];
					for (var i = 0 ; i < arr.length ; i++){
						if(arr[i].login == 'undefined') continue;
						t += arr[i].login + ':' + arr[i].last_activity + '\n';
					}
					response.headerJSON = "";
					$('active_users').innerHTML = t;
					new Effect.SwitchOff('active_users', {delay : 3});

				}
			});

}

/**
* Put focus on search field , if any
*
*/
function GetFocus(){
	if($('searchString')){
		$('searchString').focus();
	}
}

/**
* Switch display block or none on given element ID
*/
function DisplaySW(element_id){

	var e = $(element_id);

    var new_display = (e.tagName == 'TBODY') ? 'table-row-group' : 'block';

	e.style.display = (e.style.display == 'none' || e.style.display == '') ? new_display : 'none' ;

}

/**
* invoice qty =< order qty for edit qty client order
*/
function VerifInvoiceQty(formID, invoice_qty) {

	var qty = document.forms[formID].quantity.value;

	if (parseInt(qty) < parseInt(invoice_qty))
		document.forms[formID].quantity.value = invoice_qty;

}

/**
* Dynamic text area: when the cursor is at the end of the textarea,
* the textarea will grow downward
*
*/
function DynamicTextarea(t) {

	var a = t.value.split('\n');
	b=1;
	for (x=0;x < a.length; x++) {
		if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
	}
	b+= a.length;
	if (b > t.rows) t.rows = b;
}


/**
 * add product to buying cart
 *
 */
function AddToCart(_do, pid, qty){

	var url = 'ajax/ajax_cart.php?do=' + _do;
	var params = 'pid=' + pid + '&qty=' + qty;

	new Ajax.Request(url,{
				method: 'post',
				parameters: params,
				onSuccess: function(transport, json){

					var fb = $('feedback_cart');
					var scrol_top = document.viewport.getScrollOffsets().top;

					var from_top = (scrol_top - 100 <= 0) ?  0 : scrol_top-100;

					fb.style.top = 100 + (from_top) + 'px';
					fb.innerHTML = json['notice'][0];
					fb.style.display = 'block';

					$('cart_total_price').innerHTML = json['data'][0];

					new Effect.SwitchOff(fb, {delay : 4});

				}

		});

	return false;
}

/**
* Search for a client
*
*/
function SearchClient(source){

	window.open('admin/clientSearch.php?source=' + source, 'Client_finder', 'height=800, width=1200,status=yes,toolbar=no,menubar=no, location=no, scrollbars=yes, resizable=yes');

}

/** productsDisplay.php*/
function dispo(dispo){
	window.open('dispo.php?lang='+ dispo ,'Dispos','width=400,height=250');
}

/**
 *
 */
function ImgLayer(id, img, type){

// 	var layer = $('img_layer');
//
// 	if(layer == null){
//
// 		layer = new Element('div', {id : 'img_layer'});
//
// 		layer.appendChild(new Element('img', {id : 'prod_img', 'src' : 'images/blank.png'}));
// 		layer.onclick=function() {this.hide()}
// 		document.body.insert(layer);
//
// 	}

	var type = (type != '') ? type : 3;

 	$('img_layer').style.visibility = 'hidden';
 	var layer = $('img_layer');
	var id = id + '_';
	var src = $(id);
	$('prod_img').src = 'thumb/'+ img + '/' + type;

	layer.style.left = (src.measure('left') + 90)+ 'px';
	layer.style.top = src.measure('top') - 40 + 'px';
	layer.style.visibility='visible';

}

/**
 *
 */
function ImgOff(){
	$('img_layer').style.boxShadow = '0'
	$('img_layer').style.visibility = 'hidden';
	$('prod_img').src = 'images/blank.png';
}

/**
* Function for hide or show the div if more than 15 brands is displayed
*
*/
function ShowDiv(){

	var form = $('brands');

	if(form == undefined) return false;

	var checkbox = form.getInputs('checkbox');

	for (var i=15;i<checkbox.length;i++) {

		if (checkbox[i].checked == 1) {
			$('hidden_div_brands').style.display = "block";
			break;
		}
	}
}

/**
 * Lazy loader for products thumbs, it will display only pics
 * that are visibile in the portView
 *
 *
 *
 */
	function LazyLoader(){

		if (Object.isUndefined(Proto)) {var Proto = {}}
			Proto.Lazy = Class.create({
				initialize: function(options) {
					this.options = options || {};
					this.loaded = new Array();
					this.objects = $$('div.image');

					if (this.options.event !== 'click') {
						Event.observe(window, 'scroll', this.load.bind(this));
						Event.observe(window, 'resize', this.load.bind(this));
					}
					this.load();
				},
				load: function(el) {

					this.objects.each(function(el, i){

						if (!this.loaded[el.id] && this.withinViewport(el)) {
							el.style.backgroundImage = 'url(thumb/' + el.id.substring(1, 6) + '/2)';
							//el.src = '/thumb/' + el.id.substring(1, 6) + '/4';
							this.loaded[el.id] = true;
						}
						//$("debug").innerHTML += this.objects.length + ' , ';

					}.bind(this));
				},
				withinViewport: function(el) {
					var elOffset = el.cumulativeOffset(),
						vpOffset = document.viewport.getScrollOffsets(),
						elDim = el.getDimensions(),
						vpDim = document.viewport.getDimensions();
					if (elOffset[1] + elDim.height < vpOffset[1] || elOffset[1] > vpOffset[1] + vpDim.height ||
					elOffset[0] + elDim.width < vpOffset[0]  || elOffset[0] > vpOffset[0] + vpDim.width) {
						return false;
						}
					return true;
				}
			});

			document.observe('dom:loaded', function(){
					new Proto.Lazy();
					Proto.Lazy.load;
					}
			);

	}



