var system = {
	init : function () {
		
	},
	bodyOnLoad : function () {
		return;
	}	
};

var iface = {

	getMouseX : function () {
		return this.X;
	},
	getMouseY : function () {
		return this.Y;
	},
	posLoadImg : function (x,y){
		x = x - 40;
		y = y - 60;
		$('loadingimg').setStyle("top:" + y +"px; left: " + x + "px;");
		$('loadingimg').show();
	},
	hideLoadImg : function () {
		$('loadingimg').hide();
		$('loadingimg').setStyle("top: 0px; left: 0px;");
	},
	autopositionLoadingImg : function () {
		iface.posLoadImg(iface.X, iface.Y-10);
	},
	calendar: function(filed, trigger, format){
		if(!format)format = "%m/%d/%y";
		Calendar.setup({
       		inputField     :    filed,     // id of the input field
        	ifFormat       :    format,      // format of the input field
        	button         :    trigger,  // trigger for the calendar (button ID)
        	singleClick    :    true,
			firstDay	   :	1
    	});
	},
	addMoreFields: function(element){
        var table = element.parentNode.parentNode.parentNode;
        var row = table.insertRow(table.rows.length);
        var cell = row.insertCell(0);
        var content = table.rows[0].cells[0].innerHTML;
        cell.innerHTML = content;

        if (table.rows.length > 1) {
            $('removemorefields').style.display = '';
        }
        if (table.rows.length == 10) {
            element.style.display = 'none';
        }

	},
	removeMoreFields: function(element){
        var table = element.parentNode.parentNode.parentNode;
        table.deleteRow(table.rows.length-1);

        if (table.rows.length < 10) {
            $('addmorefields').style.display = '';
        }
        if (table.rows.length == 1) {
            element.style.display = 'none';
        }
	}
};
Event.observe(window, 'mousemove', function(e){
	iface.X = Event.pointerX(e);
	iface.Y = Event.pointerY(e);
});

var cart =  {
	addToCart : function (pid) {
		iface.posLoadImg(iface.X, iface.Y-10);
		
		new Ajax.Request('/',
		{
			method:'post',
			parameters: {id: pid, noheaderandfooter:1,action: 'product-addtovirtualbasket'},
		    onSuccess: function(transport){
				
		      var response = transport.responseText || 'no text';
			  		response = response.strip();	
					//alert(response);		  		
				  	if(response=='done'){
				  		if($('adderror')) $('adderror').update(response);
						cart.reloadVCart();
				  	} else {				  	
				  		if($('adderror')) $('adderror').update(response);
				  	}
					iface.hideLoadImg();
					return false;
		      },
		    onFailure: function(){
				$('adderror').update('Error: Unknown error');
			}
		  });
		  return false;
		
		
	},
	reloadVCart : function () {
		
		new Ajax.Request('/',
		{
			method:'post',
			parameters: {action: 'user-vcart',noheaderandfooter:1},
			onSuccess: function(transport){
				var response = transport.responseText || 'no text';
				//alert(response);
				$('vcart').update(response);
			}
		});
	},
	removeItem: function (itemid) {
		new Ajax.Updater('mainContent', '/index.php',{
			method:'post',
			parameters: {action: 'user-shoppingcart',noheaderandfooter:1, whattodo: 'removeitem', id: itemid},
			onComplete: function () {
				new Ajax.Updater('mainContent', '/?action=user-shoppingcart&noheaderandfooter=1');
			}
		});
		
	},
	updateQuantities : function () {
		iface.autopositionLoadingImg();
		var qinputs = $$('input.quantity');
		var params = $H();
		params.set('noheaderandfooter', 1);
		params.set('action', 'product-updatecartquantities');
		
		qinputs.each(function(s){
			params.set(s.id, s.value);
		});
	
		
		new Ajax.Request('/index.php',
		{
			method:'post',
			parameters: params,
		    onSuccess: function(transport){
		      	var text = transport.responseText;
			  	//alert(text);	
				
				//$('errordiv').update(text);
				new Ajax.Updater('mainContent', '/?action=user-shoppingcart&noheaderandfooter=1');
		      	iface.hideLoadImg();  		
			  },
		    onFailure: function(){
				$('errordiv').update('Error: Unknown error');
			}
		  });
	},
	procedeToOrder : function () {
		this.updateQuantities();
		location.assign("/?action=user-makeorder");
	}

};
var admin = {
	addProductsToNew : function () {
		var chckboxes = $$('input.productids');
		var values = $A();
		for (var i=0; i<chckboxes.length; i++){
			if(chckboxes[i].checked){
				values.push(chckboxes[i].value);
			}
		}
		var ids = values.join(",");
		new Ajax.Request('/index.php',
		{
			method:'post',
			parameters: {action: 'product-makenew',ids:ids,noheaderandfooter:1},
		    onSuccess: function(transport){
		      	var text = transport.responseText;
		      	//alert(text);
			  	if(text == 1){
					window.location.assign('/?action=document-list-product&isnew=1');
				}	
			  },
		    onFailure: function(){
				$('errordiv').update('Error: Unknown error');
			}
		  });
	},
	removeProductsFromNew : function () {
		var chckboxes = $$('input.productids');
		var values = $A();
		for (var i=0; i<chckboxes.length; i++){
			if(chckboxes[i].checked){
				values.push(chckboxes[i].value);
			}
		}
		var ids = values.join(",");
		new Ajax.Request('/index.php',
		{
			method:'post',
			parameters: {action: 'product-removeFromNew',ids:ids,noheaderandfooter:1},
		    onSuccess: function(transport){
		      	var text = transport.responseText;
		      	//alert(text);
			  	if(text == 1){
					window.location.reload();
				}	
			  },
		    onFailure: function(){
				$('errordiv').update('Error: Unknown error');
			}
		  });
	},
	addProductsInFolder : function (folderid) {
		var chckboxes = $$('input.productids');
		var values = $A();
		for (var i=0; i<chckboxes.length; i++){
			if(chckboxes[i].checked){
				values.push(chckboxes[i].value);
			}
		}
		var ids = values.join(",");
		new Ajax.Request('/index.php',
		{
			method:'post',
			parameters: {action: 'folder-addproducts', id:folderid,ids:ids,noheaderandfooter:1},
		    onSuccess: function(transport){
		      	var text = transport.responseText;
				//alert(text);
			  	if(text == 1){
					window.location.reload();
				}	
			  },
		    onFailure: function(){
				$('errordiv').update('Error: Unknown error');
			}
		  });
	},
	deleteProductImage : function (element, imagepath, id, field) {
        if (!confirm('Are you sure you want to delete this image?')) {
            return false;
        }
		var params = $H();
		params.set('action', 'document-deleteimage');
		params.set('id', id);
		params.set('noheaderandfooter', 1);
		params.set('imagepath', imagepath);
        if (field == 'primaryfile') {
            params.set('field', field);
        }
		new Ajax.Request('/index.php',
		{
			method:'get',
			parameters: params,
		    onSuccess: function(transport){
		      	var text = transport.responseText;
				//alert(text);
			  	if(text == 'done'){
					element.style.display = 'none';
					$(field + '_thumb').style.display = 'none';
				}	
			  },
		    onFailure: function(){
				$('errordiv').update('Error: Unknown error');
			}
		  });
	},
	deleteDocAttachment : function (element, attachmentpath, id, field) {
        if (!confirm('Are you sure you want to delete this attachment?')) {
            return false;
        }
		var params = $H();
		params.set('action', 'document-deleteattachment');
		params.set('id', id);
		params.set('noheaderandfooter', 1);
		params.set('attachmentpath', attachmentpath);
        if (field == 'primaryfile') {
            params.set('field', field);
        }
		new Ajax.Request('/index.php',
		{
			method:'get',
			parameters: params,
		    onSuccess: function(transport){
		      	var text = transport.responseText;
				//alert(text);
			  	if(text == 'done'){
					element.style.display = 'none';
					$(field + '_thumb').style.display = 'none';
				}	
			  },
		    onFailure: function(){
				$('errordiv').update('Error: Unknown error');
			}
		  });
	}

}
var user = {
	toggleType : function (element) {
        var user_type = element.value;
        if (user_type == 'person') {
            $('name_company_panel').style.display = 'none';
            $('identno_company_panel').style.display = 'none';

            $('name_panel').style.display = '';
            $('name2_panel').style.display = '';
            $('identno_panel').style.display = '';
            $('personal_data_title_panel').style.display = '';
            $('personal_data_panel').style.display = '';

            //disable the company fields
            $('company_name').disabled = true;
            $('company_identno').disabled = true;

            //enable the person fields
            $('name').disabled = false;
            $('name2').disabled = false;
            $('identno').disabled = false;
            $('idnumber').disabled = false;
            $('iddate').disabled = false;
            $('idregisteredby').disabled = false;
        } else {
            $('name_company_panel').style.display = '';
            $('identno_company_panel').style.display = '';

            $('name_panel').style.display = 'none';
            $('name2_panel').style.display = 'none';
            $('identno_panel').style.display = 'none';
            $('personal_data_title_panel').style.display = 'none';
            $('personal_data_panel').style.display = 'none';

            //enable the company fields
            $('company_name').disabled = false;
            $('company_identno').disabled = false;

            //disable the person fields
            $('name').disabled = true;
            $('name2').disabled = true;
            $('identno').disabled = true;
            $('idnumber').disabled = true;
            $('iddate').disabled = true;
            $('idregisteredby').disabled = true;
        }
	}
}

var Cookie = {
  daysToExpire: 30, //1 month
  set: function(name, value, daysToExpire) {
    if (daysToExpire == undefined) {
      daysToExpire = this.daysToExpire;
    }
    var expire = '';
    var d = new Date();
    d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
    expire = '; expires=' + d.toGMTString();

    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  getArray: function(name) {
    var cookie = {};
    cookies = document.cookie.split(';');
    cookies_found = 0;
    for (i=0; i<cookies.length; i++) {
        if (cookies[i].match(new RegExp(escape(name)))) {
            cookie_details = cookies[i].match(new RegExp(escape(name) + '\\s*%5B([^%]*)%5D\\s*=\\s*([^;\\s]*)'));
            cookie[cookie_details[1]] = (cookie_details ? unescape(cookie_details[2]) : '');
            cookies_found++;
        }
    }
    return (cookies_found ? cookie : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }

    Cookie.set('_test', '1');
    return (Cookie.erase('_test') = '1');
  }
};
