var email_reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
$(document).ready(function(){

	$('.tabs li a.tab').tipsy({gravity: 'w', title : 'rel',delayIn: 0, delayOut: 0});
	$('.tabs ol li a, a.delete').tipsy({gravity: 's', title : 'rel'});

	$('.tabs li a.tab').click(function(){
		$('.tipsy').remove();
		var parentLi = $(this).parent('li');
		if( parentLi.hasClass('showed') ) {
			parentLi.animate({right : '-74px'},function(){$('.tabs li').show();}).removeClass('showed');
		}
		else	{
			parentLi.animate({right : '-274px'}).addClass('showed');
			$('.tabs li').not('.showed').hide();

		}
	});
	$('.box ul li a, .menu ul li a').tipsy({gravity: 'n', title : 'rel'});
        $('div.homemassage div').css({
            'margin-top' : '-'+( $('div.homemassage div').height() / 2 )+'px'
        }).fadeIn();

        $('div.box_cont h1, div.header h1').click(function(){location.href = SITE_URL + 'atelier/';});
		$('.blank').attr('target', '_blank');
        $('#cFormButton').click( function(){sendContactEmail()} );
        $('.overlay_bg ').css({'opacity':'0.7'});

		analyticsTracking();
});

function analyticsTracking(){
	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-12220152-1']);
	_gaq.push(['_setDomainName', '.monicamw.com']);
	_gaq.push(['_trackPageview']);

	(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
}
	



function changeImageToSlider( imgUrl ){

        $('.imgContainer img').fadeOut('fast', function(){
            $(this).attr( 'src', SITE_URL+'show-image.php?file='+imgUrl+'&h=300&w=300' ).load(function(){
                 $(this).fadeIn('slow');
            })
        });

}

function showAddToCart( Name,ID ){
    showOverlay();
    $('#aptop b').text(Name);
    $('#add_product_id').val(ID);
    
    $('.addToCartPrompt').fadeIn('fast',function(){
        $(this).animate({'margin-top': '330px'});
        $('#add_product_amount').focus();
    });
}

function showOverlay() {
    scroll(0,0);
    $('body').css({'overflow' : 'hidden'});
    $('.overlay_bg').show();
}

function closeAddToCart(){
   $('.addToCartPrompt').animate({'margin-top': '-330px'},function(){
     $(this).hide();
     $('.overlay_bg ').fadeOut();
     $('body').css({'overflow' : 'visible'});
    })
}

function doAddProduct(){
	var p = new Array( $('#add_product_amount').val(), $('#add_product_id').val() )
	if( p[0] == '' || isNaN( p[0] ) ){
            alert('Por favor, ingrese la cantidad que desea agreagar al carrito de compras.');
            $('#add_product_amount').focus();
	}
	else{
            doRequest( 'addProduct' , p );
	}

}

function doRequest( callout, p ){
	$.ajax({
            type	: "POST",
            url         : SITE_URL+"classes/Json.class.php?action="+callout,
            data 	: 'Id='+ p[1] +'&amount='+ p[0],
            dataType 	: 'json' ,
            success	: function( json ) {
                            if( json.result ){location.href=SITE_URL+'ShoppingCart';}
                            else{alert('Error: Se produjo un error al intentar realizar la acción deseada.');}
                        }
    	});
	cancelAddProduct();

}

function cancelAddProduct() {
    $('#add_product_ammount').val('');
    $('#add_product_id').val('');
    closeAddToCart();
}

function login(){
    var formValues = new Array();
    var haveErrors = false;
    $('#loginForm input').each(function(){
        if( $(this).val() == '' ){
            haveErrors = true;
            $(this).css({'border-color':'red'});
        }
        else{
            formValues.push( $(this).attr('name')+'='+$(this).val() );
            $(this).css({'border-color':'#008000', 'color':'#008000'});
        }
    });
    if( haveErrors ){$('#login_notification').fadeIn();return;}
    $.ajax({
       type: "POST",
       url: SITE_URL+"classes/Json.class.php?action=login",
       data: formValues.join('&')  ,
       dataType 	: 'json' ,
       success: function( json ){
           if( json.result ){
               location.href= SITE_URL+'User';
           }else{
              $('#login_notification').text(json.Error).fadeIn();
           }
       }
    });
}

function logout(){
   $.ajax({
       type: "POST",
       url: SITE_URL+"classes/Json.class.php?action=logout",
       dataType 	: 'json' ,
       success: function( json ){
           if( json.result ){ location.href= SITE_URL; }
       }
    });
}

function sendContactEmail(){
	showOverlay();
	$('#cFormButton').text('Enviando...');
    var formValues = new Array();
    var haveErrors = false;
    $('#ContactForm input, #ContactForm textarea').each(function(){
        if( $(this).val() == ''  || ( $(this).attr('name') == 'Email' && !email_reg.test( $(this).val() ) )  ){
            haveErrors = true;
            $(this).css({'border-color':'red'});
        }
        else{
            formValues.push( $(this).attr('name')+'='+$(this).val() );
            $(this).css({'border-color':'#008000', 'color':'#008000'});
        }
    });
    if( haveErrors ){
		$('.overlay_bg ').fadeOut();
		$('body').css({'overflow' : 'visible'});
		$('#error_notification').fadeIn();
		return;
	}
    $.ajax({
       type: "POST",
       url: SITE_URL+"classes/Json.class.php?action=sendContactEmail",
       data: formValues.join('&')  ,
       success: function( msg ){ location.href= SITE_URL+'Contact/Success'; }
    });
}

function slideSwitch() {
    var $active = $('#slideshow img.active');

    if ( $active.length == 0 ) $active = $('#slideshow img:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next(): $('#slideshow img:first');
    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

function quitProduduct( Id ){
    if( confirm('Seguro que desea eliminar el producto del carrito?') ){
            $.ajax({
            type	: "POST",
            url 	: SITE_URL+'classes/Json.class.php?action=quitProduct',
            data 	: 'Id='+ Id,
            dataType 	: 'json' ,
            success	: function( json ) {
                            if( json.result ){
                                    window.location.href=SITE_URL+'ShoppingCart/';
                            }
                            else{
                                    alert('Error: Se produjo un error al intentar realizar la acción deseada.');
                            }
                        }
    });
    }
}

function refreshCart() {
	var jsArr = new Array();
	var note = $('.note textarea').val();
	var iter = 0;
        var pId;
	$('.cart-item').each(function(){
            pId = $(this).children('.pId').val();
            jsArr[iter] = pId +'='+ $('#qty'+pId ).val();
            iter++;
	});
	$.ajax({
		type		: "POST",
		url 		: SITE_URL+'classes/Json.class.php?action=refreshCart',
		data 		: 'jsArr='+ jsArr +'&note='+ note,
		dataType 	: 'json' ,
		success		: function( json ) {
                                        if( json.result ){
                                                window.location.href=SITE_URL+'ShoppingCart/';
                                        }
                                        else{
                                                alert('Error: Se produjo un error al intentar realizar la acción deseada.');
                                        }
                                }
    	});
}

function toggleNote(){
	$('.totals .note-text,.totals textarea, .totals .note em').toggle();
}

function processOrder(){
	$('.btnContinue').text('Procesando...');
	showOverlay();
    $.ajax({
        type	: "GET",
        url 	: SITE_URL+'classes/Json.class.php?action=processOrder',
        dataType: 'json' ,
        success	: function( json ) { 
            window.location.href=SITE_URL+'ShoppingCartConfirm/Success/'+json.id;
        }
    });
}

function editData(){

	showOverlay();
	$('#editButton').text('Enviando...');
	var uId = '';
	var formValues = new Array();
    var haveErrors = false;
    $('#editUser input').each(function(){
		
		if ( ( $(this).hasClass('required') && $(this).val() == '' ) ||  
				$(this).hasClass('email') && !email_reg.test( $(this).val() ) 
			){
            haveErrors = true;
            $(this).css({'border-color':'red'});
        }
        else{
			if( $(this).attr('name')!='UserId' && $(this).val() != '' ){
				formValues.push( $(this).attr('name')+'='+$(this).val() );
				$(this).css({'border-color':'#008000', 'color':'#008000'});
			}
        }
    });
	
	if( haveErrors ){
		$('.overlay_bg ').fadeOut();$('body').css({'overflow' : 'visible'});$('#error_notification').fadeIn();
		$('#editButton').text('Cambiar');
	}
	else{
		
		if( $('#UserId').val() != ''){
			uId = '&UserId='+$('#UserId').val();
		}

		$.ajax({
		   type: "POST",
		   url: SITE_URL+"classes/Json.class.php?action=saveData"+uId,
		   data: formValues.join('&')  ,
		   dataType : 'json',
		   success: function( msg ){ 
				if( msg.result ) {
					location.href= SITE_URL+'User/Edit/Success';
				}
				else{
					$('.overlay_bg ').fadeOut();$('body').css({'overflow' : 'visible'});$('#editButton').text('Cambiar');
					$('#error_notification').text(msg.Error);
					$('#error_notification').fadeIn();
				}
		   }
		});
	}
}









