var $url_colecction = false;
jQuery(document).ready(function($) {
	
	$("#add_card_form").submit(function(){		
			
		$.ajax({
			type: 'POST',
			url: "/",
			success: function(){ $("#add_card").fadeOut('normal',function(){ $("#saldo_card").fadeIn(); }); }
		});
		
		return false;
	});
	
	$("#loginbox a.add_card").click(function(){		
		$("#add_card .text").val('');
		$("#saldo_card").fadeOut('normal',function(){ $("#add_card").fadeIn(); });
		return false;
	});
	
	/* Registro */
	$("#registro input#UserLogin").keyup(function(){
		var $t = $(this);
		
		$("span#CopyUsername").html($t.val());
	});
	/* /Registro */
	
	/* Tab Menú */
	$("#tabmenu a").click(function(){
		var $t = $(this);
		var $tab = $t.attr('href').replace('#','');
		var $li = $t.parent('li');
		var $li_a = $('#tabmenu li.active');
		var $tab_a = $li_a.children('a').attr('href').replace('#','');
		var $m = $('#tabmenu');
		
		if( !$li.hasClass('active') ){
			$li.addClass('active');
			$li_a.removeClass('active');
			$('#'+$tab).removeClass('hide').addClass('show');
			$('#'+$tab_a).addClass('hide').removeClass('show');
		}
		
		return false;
	});
	/* /Tab Menú */

	/* Producto Catálogo */
	$("#product a.zoom:first").addClass('hover');
	$('#product .views img').mouseover(function(){
		var $t = $(this);
		var $src = $t.attr('src');
		if( $('#product img.big').attr('src') != $src ){
			$('#product .views a').removeClass('hover');
			$t.parent('a').addClass('hover');
			$('#product img.big').fadeOut('fast',function(){ $(this).attr('src',$src).fadeIn('fast'); });
		}
		
	});
	
	if( $('#product').is('div') ){
		$('#product a.big').click(function(){ $("#product a.zoom.hover").click(); return false; });
		$("#product a.zoom").fancybox();
	}
	/* /Producto Catálogo*/
	
	/* Buscador Catálogo */
	if ( $('#search_catalog').is('div') ){
		/*$("#search_product").autocomplete({
			source: function(request, response) {
				$.ajax({
					url: page_root+"products/search.json",
					dataType: "json",
					data: "cadena="+request.term,
					success: function(result) {
						response($.map(result, function(item) {
							return {
								label: item.name,
								value: item.name,
								url: item.url
							}
						}));
					}
				})
			},
			minLength: 3,
			select: function(event, ui) {
				//console.log(ui.item ? ("Selected: " + ui.item.url) : "Nothing selected, input was " + this.value);
				document.location = page_root+'products/view/'+ui.item.url;
			}
		});*/
		
		$("#search_product").live('click', function(){
			$(this).autocomplete({
				source: function(request, response) {
					$.ajax({
						url: page_root+"products/search.json",
						dataType: "json",
						data: "cadena="+request.term,
						success: function(result) {
							response($.map(result, function(item) {
								return {
									label: item.name,
									value: item.name,
									url: item.url
								}
							}));
						}
					})
				},
				minLength: 3,
				select: function(event, ui) {
					//console.log(ui.item ? ("Selected: " + ui.item.url) : "Nothing selected, input was " + this.value);
					document.location = page_root+'products/view/'+ui.item.url;
				}
			});
		});
		
	}
		
	
	/* /Buscador Catálogo */
	
	/* Plantillas */
	
	/* Selector Background */
	$("#plantilla .background a.mostrar").click(function(){
		var $t = $(this);
		$("#plantilla .background li").removeAttr('style');
		var $p = $(this).parent().css('z-index','15');
		var $o = $t.next();
		if( $o.is(':hidden') ){
			$o.fadeIn(250);
			if ( $o.find('li').length < 3 ){ $o.addClass('noscroll'); }
			$o.hover(null,function(){ $o.fadeOut(); });
		}
		
		return false;
	});
	
	$("#plantilla .background a.select").click(function(){
		var $t = $(this);
		var $thumb = $t.children('.thumb').attr('src');
		
		$("#plantilla .selected").fadeIn().children('.placeholder').children('img').attr('src',$thumb);
		$url_colecction = page_root+'/maker/'+$t.attr('rel');
	});

	$('#m_goto_maker').click(function(){
		if( !$url_colecction ){
			alert('No se ha elegido una colección'); 
			return false;		
		}
		document.location =  $url_colecction; 
	});

	/* /Selector Background */
	
	/* Imágenes */
	$('#viewimg .listimg li').hover(function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); });
	/* /Imágenes */
	
	var reorder_sizes_revelado = function($parent){

		var $i = 0;
		$parent.children('.size_option').each(function(){
			var $t = $(this);
			var $hidden = $t.find('input[type=hidden]');
			var $sizes = $t.find('.size');
			var $amount = $t.find('.amount');
			
			var hidden_newname = $hidden.attr('name').replace(/\[([0-9])\]\[([0-9])\]/g,"[$1]["+$i+"]");
			$hidden.attr('name',hidden_newname);
			
			var sizes_newname = $sizes.attr('name').replace(/\[([0-9])\]\[([0-9])\]/g,"[$1]["+$i+"]");
			$sizes.attr('name',sizes_newname);
			
			var amount_newname = $amount.attr('name').replace(/\[([0-9])\]\[([0-9])\]/g,"[$1]["+$i+"]");
			
			$amount.attr('name',amount_newname);
			console.log('Hidden: '+hidden_newname);
			console.log('Sizes: '+sizes_newname);
			console.log('Amount: '+amount_newname);
			/*$hidden.attr('name','data[GalleriesPhotos]['+$i+'][');
			$hidden.attr('name','data[GalleriesPhotos]['+$i+'][');	*/		
			$i++;
		});
			
		$parent.children('.size_other').each(function(){
			var $t = $(this);
			var $hidden = $t.find('input[type=hidden]');
			var $sizes = $t.find('.size');
			var $amount = $t.find('.amount');
			
			var hidden_newname = $hidden.attr('name').replace(/\[([0-9])\]\[([0-9])\]/g,"[$1]["+$i+"]");
			$hidden.attr('name',hidden_newname);
			
			var sizes_newname = $sizes.attr('name').replace(/\[([0-9])\]\[([0-9])\]/g,"[$1]["+$i+"]");
			$sizes.attr('name',sizes_newname);
			
			var amount_newname = $amount.attr('name').replace(/\[([0-9])\]\[([0-9])\]/g,"[$1]["+$i+"]");
			
			$amount.attr('name',amount_newname);
			console.log('Hidden: '+hidden_newname);
			console.log('Sizes: '+sizes_newname);
			console.log('Amount: '+amount_newname);
			/*$hidden.attr('name','data[GalleriesPhotos]['+$i+'][');
			$hidden.attr('name','data[GalleriesPhotos]['+$i+'][');	*/		
			$i++;
		});
	
	}
	
	$('#revelado img.plus_size, #revelado img.plus_other').click(function(){
		var $clone = $(this).prev().prev();
		$clone.clone().insertAfter($clone);
		
		var $parent = $(this).parent();
		
		reorder_sizes_revelado($parent);
		
		var $class_div = ( $(this).hasClass('plus_size') ) ? 'size_option' : 'other_option' ;
		
	});
	
	$('#revelado img.delete_size, #revelado img.delete_other').click(function(){
		var $clone = $(this).prev();
		var $parent = $(this).parent();
		
		var $class_div = ( $(this).hasClass('delete_size') ) ? 'size_option' : 'other_option' ;
		
		if($parent.children('.'+$class_div).length == 1)
			return false;
		
		$clone.remove();
		
		reorder_sizes_revelado($parent);
	});
	
	/* Tooltips	*/
	$('a[href][title],img[title],input[type=image][title]').qtip({
	content: {
	 text: false // Use each elements title attribute
	},
	position: { target: 'mouse', mouse: true },
	tip: true,
	style: 'cream' // Give it some style
	});
	
	$('#plantillas').qtip({
		content: { text: 'Haga Click para elegir plantilla y empezar su proyecto' },
		show: { ready: true },
		style: { textAlign: 'center', name:'cream'},
		tip: true,
		position: {
			corner: {
				target: 'bottomMiddle',
				tooltip: 'topMiddle'
			}
		},
		api: {
            onHide: function()
            {
               $('#plantillas').qtip("disable");
            }
         }
	});
	
});


function utf8_encode ( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function base64_encode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    data = this.utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}

function base64_decode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}

    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);

    return dec;
}

