CB.fn.exists = function(){return this.length>0;}

function setRadioButtonsEvents(){
	CB('.radio input[type=radio]').off('click');
	CB('.radio input[type=radio]').click(function(){
		CB(this).closest('.radgroup').find('input[type="hidden"]').val(CB(this).val());		
	});
}
function replaceAll( text, busca, reemplaza ){
	if (busca==reemplaza) return text;
	while (text.toString().indexOf(busca) != -1)
	    text = text.toString().replace(busca,reemplaza);
	return text;
}

function getNumber(valor){
	retorno=replaceAll(valor,thousand_number_format,'');
	return Number(replaceAll(retorno,decimal_number_format,'.'));
}
var aw_number=10000;
var sections_counter=2;
function sec_add(idsection){
	/* TABS Si se descomenta cambiar a jquery lo que haya de mootools
	var sect=sections.get(idsection);
	if (sect.getLimitSections()>0 && 
			sect.getLimitSections()<=CB('div[sec]').length ){
		alert(getLangTrads('CB_LIMIT_SECTION')+' '+sect.getLimitSections());
		return false;
	}
	var section_layout=$('sec_layout_'+idsection);
	var li_elem=new Element('li',{'sec':sections_counter});
	var a_li_elem=new Element('a',{'href':'#s'+sections_counter,'data-toggle':'tab'});
	a_li_elem.set('html',sect.name);
	var del_button=new Element('button',{'class':'close','secAttr':sections_counter,'secId':idsection});
	del_button.set('html','&times;');
	del_button.setStyle('margin-right','3px');
	del_button.addEvent('click',function(elem){sec_del($(this).get('secAttr'),$(this).get('secId'));});
	li_elem.adopt(del_button);
	li_elem.adopt(a_li_elem);
	$('sec_ext_'+idsection).getElement('ul').adopt(li_elem);
	
	var div_elem=new Element('div',{id:'s'+sections_counter,'sec':sections_counter});
	div_elem.addClass('tab-pane');
	div_elem.addClass('fade');
	div_elem.addClass('in');
	div_elem.adopt(section_layout.getFirst().clone(true,true));
	
	$('sec_ext_'+idsection).getElement('div.tab-content').adopt(div_elem);
	
	CB('#sec_ext_'+idsection+' ul li a:last').tab('show');
	
	setSecLinked(sections_counter);
	setRadioButtons(sections_counter);
	setRadioButtonsEvents();	
	sections_counter++;	
	executePosSection(CB('#sec_ext_'+idsection));
	*/
	var sect=sections.get(idsection);
	if (sect.getLimitSections()>0 && 
			sect.getLimitSections()<=CB('div[sec]').length ){
		alert(getLangTrads('CB_LIMIT_SECTION')+' '+sect.getLimitSections());
		return false;
	}
	var section_layout=CB('#sec_layout_'+idsection+' #clonable').clone();
	var wrapper=CB('<div id="s'+sections_counter+'" sec="'+sections_counter+'"><div class="cb_delete"><button class="btn btn-mini btn-danger" onclick="javascript:deleteSection(this);" type="button">'+getLangTrads('DELETE')+'</button></div></div>');
	wrapper.append(section_layout);
	if (secposition=='0')
		CB('#sec_ext_'+idsection).append(wrapper);
	else 
		CB('#sec_ext_'+idsection).prepend(wrapper);
	setSecLinked(sections_counter);
	setRadioButtons(sections_counter);
	setRadioButtonsEvents();	
	sections_counter++;	
	executePosSection(CB('#sec_ext_'+idsection));
	activateInputMask();	
	setTimeout(function(){	
		CB('#sec_ext_'+idsection).find('select').each(function(i,e){
			CB(e).trigger('change');		
		});
	},1500);
	
	var addinline=CB('#sec_ext_'+idsection).data('addinline');
	if(addinline=='1'){
		var seed=replaceAll(CB('#sec_ext_'+idsection).closest('form').attr('name'),'calc_adminForm','');
		var strFun = 'reloadInlines'+seed;
		var fn = window[strFun];	 
		fn();	
	}		
}

function deleteSection(elem){
	var seed=replaceAll(CB(elem).closest('form').attr('name'),'calc_adminForm','');
	var delinline=CB(elem).closest('div.secgroup').data('delinline');
	CB(elem).closest('div[sec]').remove();
	if(delinline=='1'){
		var strFun = 'reloadInlines'+seed;
		var fn = window[strFun];	 
		fn();	
	}		
}

function activateInputMask(){
	if (!(CB.browser.msie && (CB.browser.version=='7.0'||CB.browser.version=='8.0')))
		CB('input[type="text"]').setMask({attr: 'mask'});
}

function setSecLinked(sections_counter){
	CB('#s'+sections_counter).find('.mvlnkd').each(function(index,elem){
		var rnd=Math.floor((Math.random()*1000000)+1); ;
		var prev_opt=CB(elem).attr('mv_ant');		
		//CB(elem).closest('.tab-pane').find('select[mv_fld="'+prev_opt+'"]').attr('mv_fld',rnd);		
		CB(elem).closest('[sec]').find('select[mv_fld="'+prev_opt+'"]').attr('mv_fld',rnd);
		CB(elem).attr('mv_ant',rnd);	
		var seed=replaceAll(CB(elem).closest('form').attr('name'),'calc_adminForm','');
		addMultiLinkedFunction(elem,seed);		
	});
	CB('#s'+sections_counter).find('.typeahead').each(function(index,elem){
		addAutoCompleterFunction(elem);
	});		
	CB('#s'+sections_counter).find('div.cbdate').each(function(index,elem){
		if(CB.type(CB(elem).attr('id'))=== "undefined"){		
			var rnd=Math.floor((Math.random()*1000000)+1); 
			CB(elem).find('input').prop('id','input_'+rnd);
			CB(elem).find('span').prop('id','button_'+rnd);
			setCalendarCB('input_'+rnd, 'button_'+rnd);						
			//setCalendarCB('input_'+rnd, null);
		}
	});	
}

function setRadioButtons(sections_counter){
	CB('#s'+sections_counter).find('.radgroup').each(function(index,elem){
		var rnd=Math.floor((Math.random()*1000000)+1); ;
		CB(elem).find('input[type="radio"]').attr('name','r_'+rnd);
	});
}

function setCalendarCB(inputf, buttonfield){
	//Calendar.setup({'inputField':inputf,'ifFormat':getDateFormat(),'button':buttonfield});
	if (CB("#"+inputf).length){
		CB("#"+inputf).datepicker({
			dateFormat: getDateFormat(),
			showAnim: 'blind'		
		});	
	}
	// Date default as today
	//CB("#"+inputf).datepicker('setDate', new Date());
}


function sec_del(section,idsection){
	//$$('#sec_ext_'+idsection+' *[sec="'+section+'"]').each(function(elem){elem.destroy();});
	CB('#sec_ext_'+idsection).find('*[sec="'+section+'"]').each(function(index,elem){CB(elem).remove();});
	CB('#sec_ext_'+idsection+' ul li a:last').tab('show');
}

// Deprecated
function getCBFormValue(id){
	//return $$('[name=fld_'+id+']')[0];	
	return CB('[name=fld_'+id+']')[0];
}
function getCBFormValueIndex(id,index){
	//return $$('[name=fld_'+id+']')[index];	
	return CB('[name=fld_'+id+']')[index];
}
function getCBFormValueArray(id){
	//return $$('[name=fld_'+id+']');
	return CB('[name=fld_'+id+']');
}

function getCBFormValueByName(name){
	//return $$('[fldname='+name+']')[0];	
	return CB('[fldname='+name+']')[0];
}
function getCBFormValueIndexByName(name,index){
	//return $$('[fldname='+name+']')[index];	
	return CB('[fldname='+name+']')[index];
}
function getCBFormValueArrayByName(name){
	//return $$('[fldname='+name+']');
	return CB('[fldname='+name+']');	
}
// End Deprecated


function cb_setValue(name,value){
	var elem=CB('[fldname="'+name+'"]');
	var elem_tag=CB(elem).get(0).tagName;	
	switch(elem_tag){
		case 'INPUT':
			var elem_type=CB(elem).attr('type');			
			if (elem_type.toUpperCase()=='CHECKBOX'){
				CB('[fldname="'+name+'"]').each(function(index,checkbox){
					if (CB(checkbox).val()==value){
						CB(checkbox).attr('checked','checked');
					}
				});				
			} else {
				CB('[fldname="'+name+'"]').val(value);
			}
			break;
		case 'SELECT':
			CB('[fldname="'+name+'"] option[mv_option="'+value+'"]').attr("selected","selected") ;
			break;
		default:			
			CB('[fldname="'+name+'"]').val(value);
			break;
	}	
	return false;
}

function cb_getValue(name){
	var elem=CB('[fldname="'+name+'"]');
	var elem_tag=CB(elem).get(0).tagName;
	var result;	
	switch(elem_tag){
		case 'INPUT':
			var elem_type=CB(elem).attr('type');			
			if (elem_type.toUpperCase()=='CHECKBOX'){
				var ret=new Array();
				var i_ret=0;
				CB('[fldname="'+name+'"]:checked').each(function(index,checkbox){
					ret[i_ret++]=CB(checkbox).val();
				});	
				return ret;				
			} else {
				result=CB('[fldname="'+name+'"]');
			}
			break;
		case 'SELECT':
			result=CB('[fldname="'+name+'"] option:selected') ;
			break;
		default:			
			result=CB('[fldname="'+name+'"]');
			break;
	}
	var tmp_res=new Array();
	CB(result).each(function(index,elem){
		if(CB(elem).get(0).tagName=='OPTION')
			tmp_res[index]=CB(elem).attr('mv_option');
		else
			tmp_res[index]=CB(elem).val();
	});
	if (tmp_res.length==0) return '';
	else if (tmp_res.length==1) return tmp_res[0];
	else return tmp_res;
}

function showAlertDialog(msg){
	CB('#cb_error_msg').html('<p><span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;"></span>'+msg+'</p>');
	CB(function() { 
		CB( "#cb_error_modal" ).dialog({ 
			modal: true, 
			buttons: {
				Ok: function() {CB(this).dialog( "close" );}
			}
		});
	});
}

function getFormJSON(idform){
	var mainFieldsTmp=new Array();	
	CB('#'+idform+' .cb_layout_wrapper > *:not(.tabbable)').each(function(index,elem){
		CB(elem).find('input, select, textarea').each(function(i,einput){
			mainFieldsTmp.push(einput);
		});		
	});
	var mainFields=getInputWrapper(mainFieldsTmp);
	var tabFields=new Array();
	CB('#'+idform+' .cb_layout_wrapper').find('div[id^=sec_ext]').each(function(index,elem){
		var tmpTab=new Object();
		tmpTab.id=CB(elem).attr('id');
		var arrTmpTabs=new Array();
		CB(elem).find('div[sec]').each(function(ipane,elempane){
			arrTmpTabs.push(getInputWrapper(CB(elempane).find('input, select, textarea')));
		});
		tmpTab.val=arrTmpTabs;
		tabFields.push(tmpTab);
	});
	var ret=new Object();
	ret.main=mainFields;
	ret.sec=tabFields;	
	return JSON.stringify(ret);	
}

function getInputWrapper(fields){
	var arrReturn=new Array();
	for(var i=0;i<fields.length;i++){
		var field=fields[i];
		if (CB.type(CB(field).attr('name'))=== "undefined") continue;
		if (CB(field).is('input') || CB(field).is('textarea')){
			var innerVal='';			
            if (CB(field).is('input[type=checkbox]:not(:checked)') && CB(field).data('type')=='yesno'){
                innerVal='N';
            } else if (CB(field).is(':checked')) {
                innerVal=CB(field).val();
            } else {innerVal=CB(field).val();}
            var tmp=new Object();
            tmp.name=CB(field).attr('name');
            tmp.val=innerVal; 
			/*
			if (CB(field).is('input[type=checkbox]:not(:checked)')) continue;
			var tmp=new Object();
			tmp.name=CB(field).attr('name');
			tmp.val=CB(field).val();*/
			arrReturn.push(tmp);
		} else if (CB(field).is('select')){
			var tmp=new Object();
			tmp.name=CB(field).attr('name');
			tmp.val=CB(field).find(':selected').val();
			arrReturn.push(tmp);
		}
	}
	return arrReturn;
}

function getVars(idform){
	var ret=new Array();
	CB('#'+idform).find('input,textarea').each(function(index,elem){
        var elem_selected='';        
        if (CB(elem).attr('type')=='radio'){
        	elem_selected=CB(elem).attr('checked')?CB(elem).val():'';
        } else if (CB(elem).attr('type')=='checkbox'){
        	if (CB(elem).is(':not(:checked)') && CB(elem).data('type')=='yesno'){
        		elem_selected='N';
        	} else if (CB(elem).is(':checked')){
        		elem_selected=CB(elem).val();
        	}        	        	
        } else {
            if (typeof CB(elem).attr('mask')=='string' && (CB(elem).attr('[mask=""]') || CB(elem).attr('mask')!='')){
                //elem_selected=CB(elem).unmaskedVal();
                elem_selected=CB(elem).unsetMaskNew();
            } else {
                elem_selected=CB(elem).val();
            }
        }
        if (elem_selected!=''){
            ret.push(CB('<input type="hidden" name="'+CB(elem).attr('name')+'" value="'+elem_selected+'"></input>'));
        }
    }); 
	/*CB('#'+idform).find('input,textarea').each(function(index,elem){
		var elem_selected='';
		if (CB(elem).attr('type')=='checkbox' || CB(elem).attr('type')=='radio'){
			elem_selected=CB(elem).attr('checked')?CB(elem).val():'';
		} else {			
			if (typeof CB(elem).attr('mask')=='string' && (CB(elem).attr('[mask=""]') || CB(elem).attr('mask')!='')){
				//elem_selected=CB(elem).unmaskedVal();			
				elem_selected=CB(elem).unsetMaskNew();
			} else {
				elem_selected=CB(elem).val();
			}
		}							
		if (elem_selected!=''){
		    ret.push(CB('<input type="hidden" name="'+CB(elem).attr('name')+'" value="'+elem_selected+'"></input>'));			
		}
	});*/
	
	CB('#'+idform).find('select').each(function(index,elem){        
		if(CB(elem).val()!=null){
			ret.push(CB('<input type="hidden" name="'+CB(elem).attr('name')+'" value="'+CB(elem).val()+'"></input>'));
		}
	});
	ret.push(CB('<input type="hidden" name="cb_alldata" value=\''+getFormJSON(idform)+'\'></input>'));
	return ret;
}

function setDataInForm(idform,data){	
	var elems=JSON.parse(data);
	//main
	for(var i=0;i<elems.main.length;i++){
		var inelem=elems.main[i];
		CB('#'+idform).find('[name="'+inelem.name+'"],[name="'+inelem.name+'[]"]').each(function(index,field){			
			if (CB(field).is('input[type=checkbox]')){		
				if (CB(field).val()==inelem.val){CB(field).attr('checked','checked');}
			} else if(CB(field).is('input[type=hidden]')){ 
				CB(field).closest('.radgroup').find('input[type="radio"]').each(function(irad, erad){
					if (CB(erad).val()==inelem.val){
						CB(erad).attr('checked','checked');
						CB(erad).click();
					} else {
						CB(erad).removeAttr('checked');
					}
				});		
			} else if (CB(field).is('select')){
				CB(field).val(inelem.val);
				CB(field).change();
			} else if (!CB(field).is('input[type=radio]')) {
				CB(field).val(inelem.val);
			} else if (CB(field).is('textarea')){				
				CB(field).html(inelem.val);
				CB(field).change();
			} else{//console.log(CB(field));				
			}
		});
	}
	for(var i=0;i<elems.sec.length;i++){
		var section=elems.sec[i];
		var secid=section.id;
		CB('#'+secid).find('[sec]').each(function(index,elem){CB(elem).remove();});
		secid=secid.replace('sec_ext_','');		
		for(var s=0;s<section.val.length;s++){
			sec_add(secid);
			var secField=section.val[s];
			var tabcontent=CB('#sec_ext_'+secid+' div[sec]:last');
			for(var f=0;f<secField.length;f++){
				var inelem=secField[f];
				CB(tabcontent).find('[name="'+inelem.name+'"]').each(function(index,field){	
					if (CB(field).is('input[type=checkbox]')||CB(field).is('input[type=radio]')){				
						if (CB(field).val()==inelem.val){CB(field).attr('checked','checked');}
					} else if(CB(field).is('input[type=hidden]')){
						CB(field).closest('.radgroup').find('input[type="radio"]').each(function(irad, erad){
							if (CB(erad).val()==inelem.val){
								CB(erad).attr('checked','checked');
								CB(erad).click();
							} else {
								CB(erad).removeAttr('checked');
							}
						});						
					} else if (CB(field).is('select')){
						CB(field).val(inelem.val);
						CB(field).change();
					} else {
						CB(field).val(inelem.val);
					} 
				});
			}
		}
	}
}
function executePosSection(section){
	var postSection=CB(section).closest('form').find('input[name="postSection"]').val();
	if (postSection.length>0){
		var fn = window[postSection];
		fn();
	}
	var postSection2=CB(section).closest('form').find('input[name="postSection2"]').val();
	if (postSection2.length>0){
		var fn2 = window[postSection2];
		fn2();
	}	
}
function cbwo(form,params,url) {
	CB('#cbft22123').remove();
	var formcbwo=document.createElement('form');
	CB(formcbwo).attr('id','cbft22123');
	CB(formcbwo).css('display','none');
	CB(form).find('input,textarea,select').each(function(index,elem){
		var elem_selected='';        
		var checkNo=false;
        if (CB(elem).attr('type')=='radio'){
        	elem_selected=CB(elem).attr('checked')?CB(elem).val():'';
        } else if (CB(elem).attr('type')=='checkbox'){
        	if (CB(elem).is(':not(:checked)') && CB(elem).data('type')=='yesno'){
        		elem_selected='N';
        		checkNo=true;
        	} else if (CB(elem).is(':checked')){
        		elem_selected=CB(elem).val();
        	}
        } else {
            if (typeof CB(elem).attr('mask')=='string' && (CB(elem).attr('[mask=""]') || CB(elem).attr('mask')!='')){
                elem_selected=CB(elem).unsetMaskNew();
            } else {
                elem_selected=CB(elem).val();
            }
        }        	
        //if (checkNo){
        	var newElem=document.createElement('input');
			CB(newElem).attr('type','hidden');
			CB(newElem).attr('name',CB(elem).attr('name'));
			CB(newElem).attr('value',elem_selected);
			CB(formcbwo).append(newElem);
        /*} else {
        	CB(formcbwo).append(CB(elem).clone());
            CB(formcbwo).val(elem_selected);	
        } */       
	});
	for(var i=0;i<params.length;i++){
		if (CB(formcbwo).find('[name="'+params[i]['key']+'"]').exists()){
			CB(CB(formcbwo).find('[name="'+params[i]['key']+'"]')).val(params[i]['value']);
		} else {
			var newElem=document.createElement('input');
			CB(newElem).attr('type','hidden');
			CB(newElem).attr('name',params[i]['key']);
			CB(newElem).attr('value',params[i]['value']);
			CB(formcbwo).append(newElem);
		}
	}
	CB(formcbwo).attr('action',url);	
	CB(formcbwo).attr('method','post');    
	CB(formcbwo).attr('target','_blank');
	CB(formcbwo).css('display','none');
	CB('body').append(formcbwo);
	CB(formcbwo).submit();
}

function changeSqlInline(route,idform,from,fromid,to,elem){
	var elem=CB('[data-ref='+elem+']');
	var tovalue=CB(to).val();
	// Create form element	 
 	var form=CB('#calc_sqlinlineintForm')
	CB(form).attr('method','post');
	vars=getVars(idform);
	CB(vars).each(function(index,elem){
		CB(form).append(elem);
	});
	CB(form).find('input[name="format"]').val('raw');	
	CB(form).find('input[name="task"]').val('calcsqlinline');
	var itemHidden=document.createElement('input');
	CB(itemHidden).attr('type','hidden');
	CB(itemHidden).attr('name','task');
	CB(itemHidden).attr('value','getInlineSql');
	CB(form).append(itemHidden);
	itemHidden=document.createElement('input');
	CB(itemHidden).attr('type','hidden');
	CB(itemHidden).attr('name','layout');
	CB(itemHidden).attr('value','calcsqlinline');
	CB(form).append(itemHidden);
	itemHidden=document.createElement('input');
	CB(itemHidden).attr('type','hidden');
	CB(itemHidden).attr('name','idfrom');
	CB(itemHidden).attr('value',fromid);
	CB(form).append(itemHidden);
	itemHidden=document.createElement('input');
	CB(itemHidden).attr('type','hidden');
	CB(itemHidden).attr('name','view');
	CB(itemHidden).attr('value','calcbuilder');
	CB(form).append(itemHidden);	
	if (CB(elem).attr('name').indexOf("[]") >= 0){ //Section
		itemHidden=document.createElement('input');
		CB(itemHidden).attr('type','hidden');
		CB(itemHidden).attr('name',CB(elem).attr('name').replace('[]',''));
		CB(itemHidden).attr('value',CB(elem).find('option:selected').val());
		CB(form).append(itemHidden);	
	}
	var elemBind=from;
	var elemTo=elem;
	CB.post(route, CB(form).serialize()).done(function(data){
		/*console.log(elem	);
		console.log(elemBind);
		console.log('----');*/
		if (elemBind.indexOf("[]") >= 0){ //Section
			if (idform.indexOf("[]") >= 0){
				var fromnew= CB(elemTo).closest('div[id="clonable"]').find('select[name="'+elemBind+'"]');
			}else{
				var fromnew= CB('select[name="'+elemBind+'"]');
			}
		} else {var fromnew=CB('#'+from);}
		CB(fromnew).empty();
		var elems=JSON.parse(data);	
		for(var i=0;i<elems.length;i++){
				var elem=elems[i];
				var option=document.createElement('option');
				CB(option).val(elem[0]);
				CB(option).attr('mv_option',elem[1]);
				CB(option).html(elem[1]);
				CB(fromnew).append(option);
		}
		CB(fromnew).change();
		//CB(fromnew).trigger('change', [{'elem':elemBind}])
    });
  	CB(form).empty();
}

(function (original) {
	CB.fn.clone = function () {
    var result           = original.apply(this, arguments),
        my_textareas     = this.find('textarea').add(this.filter('textarea')),
        result_textareas = result.find('textarea').add(result.filter('textarea')),
        my_selects       = this.find('select').add(this.filter('select')),
        result_selects   = result.find('select').add(result.filter('select'));

    for (var i = 0, l = my_textareas.length; i < l; ++i) CB(result_textareas[i]).val(CB(my_textareas[i]).val());
    for (var i = 0, l = my_selects.length;   i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;

    return result;
  };
}) (CB.fn.clone);




// Function to add a product to the cart
function addtocarteShop(){


//productId, quantity, site, lang

var productId=CB("#form_eshop input[name=product_id]").val();
var quantity=CB("#form_eshop input[name=quantity]").val();
var site=CB("#form_eshop").attr("action");
var lang="";

	
	CB.ajax({
		url: site + 'index.php?option=com_eshop&task=cart.add' + lang,
		type: 'POST',
		data: 'id=' + productId + '&quantity=' + quantity,
		dataType: 'json',
		
		success: function(json) {
		

			if (json['redirect'])
			{				
				window.location.href = json['redirect'];
			}
			if (json['success'])
			{
			
			
				window.location.href = site +"?option=com_eshop&view=cart";
				
			}
		},
		error: function(xhr, ajaxOptions, thrownError) {
			alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		}
	});
}