/**
 * 
 * Select * checkboxes
 * 
 * @param {Object} obj
 */
function selectAll(obj, classCheckbox){
	var check = obj.checked;
	$('input[@type=checkbox].'+classCheckbox).each(function (){
		this.checked = check;
	});
}
/** 
 * 
 * Add a field
 * 
 * @param {Object} elementID
 */
function addField(elementID){
	var field = $(elementID + " #field").val();
	var text  = $(elementID + " #field_text").val();
	
	var p = document.createElement("p");
		p.setAttribute("id", "field_"+field);
	var inputField = document.createElement("input");
		inputField.setAttribute("name", "field_" + field);
		inputField.setAttribute("value", text);
		inputField.setAttribute("type", "hidden");
	var delElem = document.createElement("a");
		delElem.setAttribute("href","#");
		delElem.setAttribute("onclick", "$('#field_"+ field +"').remove()");
		delElem.innerHTML = "delete";
	var content = "Field : " + field + " (" + text + ") ";
	p.innerHTML = content;
	p.appendChild(delElem);
	p.appendChild(inputField);

	if(field != "" && text != ""){
		var ok = true;
		$(elementID + " p").each( function (){
			if(this.id == "field_"+ field){
				alert("This field already exits!");
				ok = false;
			}
		});
		if(ok){
			$(p).insertBefore("#insertBefore");
		}
	}else{
		alert("Please enter both field and text values");	
	}
}
/**
 * Tree view callbacks
 * @param id
 * @return
 */
function selTreeItem(id){
	$('#parentID').val(id);
	$('#selectedParentText').html("You have selected a category. <a href='#' onclick='delTreeItem(); return false;'>Deselect</a>");
}
function delTreeItem(){
	$('#parentID').val(0);
	$('#selectedParentText').html('');
}
/**
<tr id="optionalField">
	<td>
		Field:
		<strong><span class="field_name"></span></strong>
	</td>
	<td style="padding-left: 10px;">
		Value:
		<input type="text" class="field_value" size="20" value="" />
		<a href="#" onclick="addFieldFromSuggested('#category_fields'); return false;">add</a>
	</td>
</tr>
 * @param id
 * @return
 */
function select_category(id){
	$('#categoryID').val(id); // Setting the category_id for post
	//Fetch fields of the selected category if they exist
	$.getJSON("fetchFields/" + id, function(json){
			if (json){
				$("#suggestedFields").show();
				if($("#suggestedFieldsTable")){
					$("#suggestedFieldsTable").remove();
				}
				$("#suggestedFields").append("<table id='suggestedFieldsTable'></table>");
				$.each(json, function (key, value){
					$("#suggestedFieldsTable").append($(".optionalField"));
					//console.log($("#suggestedFieldsTable > .optionalField"));
					//"Key: " + key + " Value: " + value;
				});
			}else{
				if($("#suggestedFieldsTable")){
					$("#suggestedFieldsTable").remove();
				}
			}
	});
}

/**
 * Callbacks for lists
 * 
 * Requires a method in the current controller called 'ajax' that handles the requests from the list
 *  
 */

function itemFocused(obj,field, id){
	var inputField = document.createElement("input");
		inputField.setAttribute("name", field);
		inputField.setAttribute("value", $(obj).html());
		inputField.setAttribute("size", $(obj).html().length);
		inputField.setAttribute("id", field + "_" + id);
		inputField.setAttribute("tabindex", obj.tabIndex);
		inputField.setAttribute("onblur", "itemChanged(\"" +field + "_" + id +"\", \""+$(obj).html()+"\", \""+obj.id+"\")");
	$(obj).after(inputField);
	$("#" + field + "_" + id).focus();
	$(obj).hide();
	obj.removeAttribute('tabindex');
}
function itemOver(obj,field, id){
	$(obj).css( { cursor: 'text' } );
}

function itemOut(){
	
}

function itemChanged(elemId, oldValue, anchorId){
	var field = elemId.split("_")[0]; // Field that needs to be changed
	var id = elemId.split("_")[1]; // Row id
	var url_str = "ajax/"+id+"/";
	var obj = $("#"+elemId);
	
	if (oldValue != obj.val()){//If we have a new value around we should submit it to
		$.ajax({ 
			type: "POST", 
			url: url_str, 
			data: field + "=" + obj.val(), 
			success: function(msg){
				$("#"+anchorId).html(obj.val());
			},
			error: function(msg){
				alert("Submit error");
			}
		});
	}else{
		
	}
	$("#"+anchorId).attr({ tabindex: obj.attr('tabindex')});
	$("#"+anchorId).show();
	obj.hide();
}

//Slide effects
$(document).ready(function(){
	$(".showhide").click(function () {
		$(this).parent().find("div").slideToggle("fast");
	});
});
function change_quantity(product_id,flag)
	{
		my_url = "<?=base_url()?>carts/ajax/"+product_id+"/"+flag;
		urlArray = my_url.split("/");
		product_id = urlArray[5];
		flag = urlArray[6];
		product_quantity = $('#product_quantity_'+product_id).html();
		product_quantity = parseInt(product_quantity);
		total_init = $('#total_id').html();
		total_init = parseInt(total_init);
		block_subtotal = parseInt($('#block_subtotal_'+product_id).html());
		product_price = parseInt($('#product_price_'+product_id).val());
		if (flag==1)
			{						
				total_final = parseInt(total_init+product_price);							
			}
		else if (flag==-1)
			{						
				
				if (product_quantity > 1)
				{
					total_final = parseInt(total_init - product_price);
				}	
				else
				{
					total_final = parseInt(total_init);
				}
				
			}
		else if (flag==0)
		{
			total_init = parseInt($('#total_id').html());
			total_final=total_init-block_subtotal;
			if (total_final==0)
			{
				total_final=total_init-block_subtotal;
				$('#products_block').html('COS GOL');
			}
			$('#total_id').html(total_final);
		}
		if (total_final == 0) {
			$('#total_id').html('0');
		}
		else
		{
			$('#total_id').html(total_final);
		}
		$.ajax({
			type: "GET",
			dataType:"json", 
			url: my_url,
			success: function(url) 
			{			
				if (url.success='yes')
				{
					if (url.message!='delete')
					{
						$('#cart_item_'+product_id).html(url.message);
						
					}
					else
					{
						$('#block_'+product_id).html('');						
						
					}
				}	
				
			}
		});
	};
<!--

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->
	function right(e){
		var msg = "You do not have permission to save this image.";
		if (navigator.appName == 'Netscape' && e.which == 3) {
			alert(msg);
			return false;
		}
		if (navigator.appName == 'Microsoft Internet Explorer' && event.button == 2) {
			alert(msg);
			return false;
		}
		else {
			return true;
		}
	}
	function trap(){
		if(document.images){
			for(i=0;i<document.images.length;i++){
				document.images[i].onmousedown = right;
				document.images[i].onmouseup = right;
			}
		}
	}
	function change_quantity(product_id,flag){
		my_url = "<?=base_url()?>carts/ajax/"+product_id+"/"+flag;
		urlArray = my_url.split("/");
		product_id = urlArray[5];
		flag = urlArray[6];
		product_quantity = $('#product_quantity_'+product_id).html();
		product_quantity = parseInt(product_quantity);
		
		total_init = $('#total_id').html();
		total_init = parseInt(total_init);
		block_subtotal = parseInt($('#block_subtotal_'+product_id).html());
		product_price = parseInt($('#product_price_'+product_id).val());
		if (flag==1)
			{						
				total_final = parseInt(total_init+product_price);							
			}
		else if (flag==-1)
			{						
				
				if (product_quantity > 1)
				{
					total_final = parseInt(total_init - product_price);
				}	
				else
				{
					total_final = parseInt(total_init);
				}
				
			}
		else if (flag==0)
		{
			total_init = parseInt($('#total_id').html());
			total_final=total_init-block_subtotal;
			if (total_final==0)
			{
				total_final=total_init-block_subtotal;
				$('#products_block').html(' COS GOL!');
			}
			$('#total_id').html(total_final);
		}
		if (total_final == 0) {
			$('#total_id').html('0');
		}
		else
		{
			$('#total_id').html(total_final);
		}
		
		$.ajax({
			type: "GET",
			dataType:"json", 
			url: my_url,
			success: function(url) 
			{			
				if (url.success='yes')
				{
					if (url.message!='delete')
					{
						$('#cart_item_'+product_id).html(url.message);
						
					}
					else
					{
						$('#block_'+product_id).html('');						
						
					}
				}	
				
			}
		});
	};//<!--SINCRONIZARE DROPDOWN ---> DROPDOWN ---> INPUTTEXT
	
	function getAlternateInput()
	{		
		if ($('#town').val()==0)
		{
			input = '<input type="text" id="town" name="town" ';
			fetch_error = "value="+"<?php if(isset($values['town'])): echo $values['town']; endif;?>\"  maxlength='100' class='forum_text_box'  />";
			new_input = input+fetch_error;
			$('#town').remove();
			$('#oldTownRow').add('<input type="text">');			
		}
	}
	function slide(key) 
	{		
		div = '#'+key;					
		$(div).slideToggle(400);
		return false;
	};			
	$(document).ready(function(){ 
		div = '#loginForm';				
		$(div).hide();				
	});										
	$(document).ready(function(){ 
		div = '#products_block';				
		$(div).hide();				
	});										
//<!-- VERIFICARE EXISTENTA CLIENT
	function checkClient()
	{
		email_string = $('#email').val().split('@',2);
		user = email_string[0];
		domain = email_string[1];
		$.ajax(
			{
				type:"POST",
				url:"<?=base_url()?>orders/checkClientByEmail/"+user+"/"+domain,
				success: function(msg)
				{
					if (msg=='success')
					{
						div = '#pers_details';	
						span = '#alert';				
						$(div).slideUp(400);
						div_0 = '#location';
						$(div_0).slideUp(400);
						p='<p style="background:green;">Datele dvs. exista deja in baza noastra de date. Daca doriti sa le schimbati, apasati <a href="#" onclick="showDetails()">aici</a></p>'	
						$(div).hide();
						$(span).append(p);	
									
					}
					if (msg=='failure')
					{
						div = '#pers_details';
						$('#alert').html('');	
						$(div).slideDown(400);
						div_0 = '#location';
						$(div_0).slideDown(400);
					
					}
				}
			}
			);
		
	}
	function showDetails()
	{
		
		$.ajax({
			type: "POST",
			url: "<?=base_url()?>orders/setClientDetails/",
			success: function(msg){
					
					client_array = msg.split('||',5);
					$('#first_name_id').val(client_array[0]);
					$('#last_name_id').val(client_array[1]);
					$('#phone_number_id').val(client_array[2]);
					$('#address_id').val(client_array[3]);
					$('#postal_id').val(client_array[4]);
					
					
				
			}
			
		});
		
		div_0 = '#location';
		div = '#pers_details';
		$(div).slideToggle(400);
		$(div_0).slideToggle(400);
	}
