function str_replace(busca, repla, orig)
{
	str 	= new String(orig);

	rExp	= "/"+busca+"/g";
	rExp	= eval(rExp);
	newS	= String(repla);

	str = new String(str.replace(rExp, newS));

	return str;
}

function mfwAlert(mfwTitle,text)
{
	var title = mfwTitle ? mfwTitle : 'Flugel';
	var $dialog = $('<div></div>')
	.html(text)
	.dialog({
		autoOpen: false,
		modal:true,
		title: title+' '
	});
	$dialog.dialog('open');
}


function mfwData(data)
{
	if(data.status == true){							
		if(data.redirect)
			window.location = data.redirect;
		if(data.description)
			mfwAlert(data.message,data.description);
		if(data.response){
			mfwAlert('',data.response);
		}
		if(data.id == "all"){
			form.reset(); }
		if(data.resetform){
			$('#'+data.resetform);
			$('#'+data.resetform+' input').val('');
			$('#'+data.resetform+' textarea').val('');
		}
		else if(data.id){
			$('#id'+data.id).remove(); }
	}
	else
		mfwAlert(data.message,data.description);	
}


/*****************/	
/* VALIDATION  */	
/***************/	

function ajaxForms()
{
	jQuery.each($('form'),function(ajaxForm){ 
		$(this).validate({
			rules: {
				password: {
					minlength: 5	
				},
				confirmPassword: {
					required: true,
					equalTo: "#password"
				}
			},	
			submitHandler: function(form){
				var continuar = 0;
				if($('.defaultText').length>0)
				{
					jQuery.each($('.defaultText'),function(){
						if(this.value == $(this).attr('title'))
							$(this).val('');
					});
				}
				if($(form).hasClass('ajax'))
				{
					$.ajax({
						type: 'post',
						url: $(form).attr('action'),
						data: $(form).serialize(),
						dataType: 'json',
						error:function(){
							mfwAlert('','<div class="ui-state-error ui-corner-all"><p class="Alert">Error',' Missing controller :(</p></div>');
						},
						success: function(data){
							mfwData(data);
						}
					});
				}
				else{
					form.submit();
				}
			}
		});
	});
	
}
	
$(document).ready(function(){
						   
	$("#indexTransition").delay(4000).fadeOut(500);	
	$("#home").delay(4500).fadeIn(500);	

	$('.wysiwyg').wysiwyg();
	$("a.ajaxLink").click(function(e) {
		e.preventDefault();
		if($(this).hasClass('addCart')){
				$.post(this.href, this.rel ,
				function(data)
				{ 
					if(data.status == true){
						if(data.id)
							$('#id'+data.id).remove();
						if(data.response)
								mfwAlert('',data.response);
						if(data.redirect)
							window.location = data.redirect;
					}
					else
						mfwAlert(data.message,data.description);
				}, "json");
		}
		else{
			if(confirm('Por favor, confirme el proceso.'))
			{
				$.post(this.href, this.rel ,
					function(data)
					{ 
						if(data.status == true){
							if(data.id)
								$('#id'+data.id).remove();
							if(data.response)
								mfwAlert('',data.response);
							if(data.redirect)
								window.location = data.redirect;
						}
						else
							mfwAlert(data.message,data.description);
					}, "json");
			}
		}
	});

	$("a.ajaxModal").click(function(e) {
		e.preventDefault();
		$('#site').append('<div id="ajaxModal" class="hide"></div>');
		$('#ajaxModal').load(this.href, function() {
			mfwAlert('Ingreso',$('#ajaxModal').html());
			$('#ajaxModal').remove();
			ajaxForms();
		});		
	});
	
/*****************/	
/* DATE PICKER   */	
/*****************/		

	$(".datepicker").datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'mm-dd-yy'
	});

/*****************/	
/* TABS */	
/*****************/		
	
	$(".tabs").tabs({ fx: { opacity: 'toggle', duration: 'fast' } });
	
/*****************/	
/* TOOLTIP */	
/*****************/		
	
	$('.tooltip').tooltip({showURL: false});

/*****************/	
/* HIDE AND SHOW */	
/*****************/	
	
	jQuery.each($('.hider'),function(){
		$('.'+this.id).hide();	
	});

	$('.hider').hover(function(){
		$('.'+this.id).slideToggle();
	});

/*************************/	
/* INPUT DEFAULT TEXT 	*/	
/***********************/

	function defaultText()
	{
		jQuery.each($('input.defaultText'),function(n,defaultText){
			var dValue = $(defaultText).attr('title');
			$(defaultText).val(dValue);
			$(defaultText).focus(function(){
				if($(defaultText).val() == dValue)
					$(defaultText).val('');
				$(defaultText).blur(function(inp){
					if($(defaultText).val() == '')
						$(defaultText).val(dValue);
				});
			});
		});
	}
	
	defaultText();
	
/*************************/	
/* MULTIPLE SELECTER 	*/	
/***********************/
	
	jQuery.each($('.multipleLink'),function(){
		$(this).click(function(e){
							   
			e.preventDefault();
			$.each($('#'+$(this).attr('rel')+' > option'), function(index, option) { 																	
				if(option.selected)
				{	var id = $(option).val();
					var html = '<td><span></span></td>												<td><input type="text" name="porcentajes[]" class="" /><input type="hidden" name="materiales[]" value="0" /></td>												<td><a href="#" class="deleteMultipleOpt deleteLink" rel="0">&nbsp;</a></td>';
					
					if($('#id'+id).length<1 && option.value != '')
					{
						$('.multipleResult').removeClass('hide');
						html = html.replace('<span></span>','<span>'+$(option).html()+'</span>');
						html = html.replace('rel="0"','rel="'+id+'"');
						html = html.replace('value="0"','value="'+id+'"');
						html = html.replace('class=""','class="required number"');
						$('.multipleResult table tbody').append('<tr id="id'+id+'">'+html+'</tr>');
						deleteMultipleOpt();
						 
					}
				}
				
			});					   
		});
	});
	
	function deleteMultipleOpt()
	{
		$.each($("a.deleteMultipleOpt"), function(index, value) { 
			$(value).click(function(e) {
				e.preventDefault();
				$('#id'+$(this).attr('rel')).remove();
			});
		});
	}
	
	deleteMultipleOpt();

	$('.producto .galeria').after('<ul id="nav">').cycle({ 
	    pager:  '#nav', 
		next:   '.producto .galeria', 
	    pause:   1,
		// callback fn that creates a thumbnail to use as pager anchor 
		pagerAnchorBuilder: function(idx, slide) {
			var src = $(slide).children().attr('src').replace('/gallery','/thumbs');
			return '<li><a href="#"><img src="' + src + '" /></a></li>';
		}
		,
		before:coleccionDesc
	});
	
	function coleccionDesc(){
		if($('.coleccionDesc').length>0){
			$('.coleccionDesc h2').html($(this).children().attr('alt'));
		}
	}
	
	$('#slideshow').cycle('pause');
	
	$('.novedades').cycle();
	
	$('.verNovedades').click(function(e){
		e.preventDefault();
		$("#novedades").dialog({modal:true});
	});
	
	$('#codigo').change(function(e){
		$.post(site.path+'admin/validarCodigo', 'codigo='+$(this).val() ,function(data)
		{
			if(data.status==false)
			{
					mfwAlert('',data.message+'<br />'+data.description);
			}
			
		}, "json");
	});	
	
	$('.notice-img').lightBox();
	$('a[rel*=lightbox]').lightBox();

	ajaxForms();

	$('#addImage').click(function(){
		if($('.addedLiImage').length > 0){
			var newId = Number($('.addedLiImage').last().attr('id').replace('img','')) + 1;
		}
		else
			var newId = 1;
		var newImageLi = '<li class="addedLiImage" id="img'+newId+'"><label for="imagen_'+newId+'">imagen '+newId+'</label><input name="imagen_'+newId+'" id="imagen_'+newId+'" type="file" /><br /><br /><label for="texto_'+newId+'>">texto '+newId+'</label><textarea id="texto_'+newId+'" name="texto_'+newId+'" ></textarea></li>';
		$('#imagesUl ul').append(newImageLi);
	});
	
	

});
