
var cqlook = {},
	styleForm = {loader: true};

cqlook.postManager = {
	init: function() {
		if ($('#fb-rootbody').height() == null) cqlook.postManager.more();
		cqlook.postManager.pages();
	},
	more: function(){
		var maxLength = 100;
		
		
		$('.home .question h1 a.original, .answers .answerDescription a.original').each(function(){
			
			if(($(this).html().length > maxLength)&&($(this).html().indexOf('class="seeMore"')==-1)){
				var fullTxt = $(this).html();
				var smallTxt = fullTxt.slice(0,maxLength);
				$(this).parent().append('<a class="full" href="'+$(this).attr('href')+'">'+fullTxt+'</a>');
				$(this).html(smallTxt+'... <a class="seeMore">ver mais</a>')
					.attr('href','javascript:;').removeClass('original').addClass('summary');
				cqlook.postManager.expand();
			}
		});
	},
	expand: function(){
		$('.summary').click(function(){
			
			var aHref = $(this),
					article = aHref.parent().parent().parent();
					
			article.find('.full').show();
			article.find('time').show();
			
			aHref.hide();

		});
	},
	pages: function(){
		
		$('.home .paginacao a').unbind('click').bind('click', function(e){
			
			e.preventDefault();
			
			var aHref = $(this),
					nextPage = parseInt(aHref.attr('data-next-page'), 10);
			
			if (aHref.hasClass('loading'))
				return;
			
			aHref.addClass('loading');
			
			$('.home ul.questions-list:first').append('<div class="paginado nextPage' + nextPage + '"></div>');
			
			var url = aHref.attr('href'),
					sortValue = $('.sort option:selected').val();
					
			if (sortValue !== '') {
				url = url + '&order_by=' + sortValue;
			}					

			$('.home ul.questions-list:first .nextPage' + nextPage).
				load(url + ' ul.questions-list', function(result){
					
					if (result.indexOf('li class="question-li') === -1) {
						
						aHref.
							removeClass('loading').
							addClass('text').html('- Não há mais dúvidas -').
							attr('href','javascript:;').css('cursor','default');
						window.setTimeout("$('.home .paginacao a').animate({opacity: '0'}, 500, 'linear');",2000);
					}
					
					else {
						
						var snippet = $('.paginacao a').attr('href').split('&page=')[0];
						
						if (snippet.indexOf('post_type') > 0 || snippet.indexOf('text') > 0) {
							snippet = snippet + '&' + 'page=' + (nextPage + 1);
						}
						else {
							snippet = '?page=' + (nextPage + 1);
						}
						
						aHref.
							attr('href',snippet).
							attr('data-next-page',(nextPage + 1)).
							removeClass('loading');
					}
				
				
				// init functions post

				var newMedias = $('.questions-list:last .media[data-post-id], .questions-list:last .answerMediaList[data-post-id]'),
						newTotal = newMedias.length,
						current = 0;
						
				newMedias.each(function(){
				
					var postId = $(this).attr('data-post-id');
					
					$.getJSON('/services/post/get_media_navigator_json',{post_id: postId}, function(json){
						
						current++;
						homeMedias[postId] = new mediaNavigator($.parseJSON(json.data), 12, 39);
						
						if (current >= newTotal) {
							
							cqlook.homeMediasNavigator(homeMedias)			
						}
					});
				});
				
				post.init();
				cqlook.postManager.more();
				answerMediaList();
				$('.inputPlaceHolder').inputPlaceHolder();
				Cufon.refresh();
			});
		});
	}
};


/* Loader */
cqlook.loader = function() {
	var el, overlay;
	return {
		init: function() {
			el = $("#loader")
			el.overlay({
				top: '40%', closeOnClick: false, closeOnEsc: false,	
				mask: { color: '#ffffff', loadSpeed: 300, opacity: 0.9 }
			});
			overlay = el.data('overlay');
			return this;		
		},
		
		show: function() {
			overlay.load();
		},
		
		hide: function(fn) {
			fn = fn || function() {};
			overlay.onClose = function() {
				fn();
				overlay.onClose = function() {};
			};		
			overlay.close();
		}
	};
}();

var mediaNavigator = function(data, startOffset, offSet){
	
	this.setId = function(postId) {
		
		this.element = $('div.media[data-post-id=' + postId + ']');
		this.postId = postId;
	};
	
	this.display = function(index) {
		
		var that = this;
		
		var media = data[index];
		
		this.element.attr('data-index', index);
		
		this.element.find('.mediaArrow').animate({'left': (index * offSet) + startOffset}, 'slow');
				
		if (media.is_image) {
			this.element.find(".mediaDetail").empty().append("<img src='/media/thumbs/308x308/" + media.uri + "' data-media-uri='" + media.uri + "' />");
		}
		else {
			this.element.find(".mediaDetail").empty().append("<div class='swfNavigator' />");
			this.element.find(".mediaDetail").find(".swfNavigator").flashembed("/swf/playback.swf", {
				MEDIA_SOURCE: media.source_type,
				VIDEO_URL: media.uri,
				THUMBNAIL: true,
				DOUBT_ID: that.postId,
				INDEX: index,
				CALLBACK: 'openModalMedia'
				
			});           
		}
	};
	
	this.getMediasNumber = function() {
		return data.length;
	};
	
	this.getMedias = function() {
		return data;
	};
	
	this.getMedia = function(index) {
		return data[index];
	};
};

cqlook.homeMediasNavigator = function(homeMedias) {

	for (var postId in homeMedias) {
		
		var navigator = homeMedias[postId];
		navigator.setId(postId); 
		navigator.display(0);
	}
	
	$('.mediaList').each(function(i, el){
	 
    var imgs = $(el).find('li img'),
				postId = imgs.parent().parent().parent().next().attr('data-post-id');
				
		imgs.unbind('click').click(function(){
		
			var index = $(this).index('div.media[data-post-id=' + postId + '] .mediaList li img');
			homeMedias[postId].display(index);
		});
	});
};

cqlook.showMessageModal = function(msg, type, onClose) {
	
	onClose = onClose || function() {};
	type = type || 'ok';
	var modal = $('#messageModal');
	
	modal.find('#txtMessageModal').attr('class','').addClass(type).html(msg);
	modal.data("overlay").onClose = onClose;
	modal.data("overlay").load();
	
	return modal;
};

cqlook.showModal = function(msg) {
	var modal = $('#messageModal');
	modal.addClass('interactModal');
	modal.find('#txtMessageModal').html(msg);
	modal.data("overlay").load();
};

styleForm.init = function() {
	
	// Bug IE8 na seleção do click dos sliders
	$('body').bind('selectstart', function(e) { return $(e.target).is(':input'); });
		
	$('#is_private').click(function(){
		ChooserRegistry.setStatus('is_private', $(this).is(':checked'))
	});
	
	$('#customer_weight').rangeinput({
		change: function() {
			ChooserRegistry.setStatus('weight', this.getValue());
		}
	});
	
	$('#customer_height').rangeinput({
		change: function() {
			var height = this.getValue();
			ChooserRegistry.setStatus('height', height);
			adjustHeightPrecision();
		}
	});
	
	$('.stepDown').click(function(e){
		var range = $(this).next().data('rangeinput'),
				measure = $(this).next().next().attr('id').split('_')[1], 
				value;
		range.stepDown(1);
		value = range.getValue();
		ChooserRegistry.setStatus(measure, value);
		$(this).parent().find(':hidden').val(value);
		adjustHeightPrecision();
	});	
	
	$('.stepUp').click(function(e){
		var range = $(this).prev().data('rangeinput'),
				measure = $(this).prev().attr('id').split('_')[1],
				value;
		range.stepUp(1);
		value = range.getValue();
		ChooserRegistry.setStatus(measure, value);
		$(this).parent().find(':hidden').val(value);
		adjustHeightPrecision();		
	});	
	
	var adjustHeightPrecision = function(height) {
		
		var height = $('#customer_height').val(),
				p = height.toString().split('.'),
				snippet;

		if (p.length === 1) {
			snippet = p[0] + '.00';
		}
		else if(p[1].length >=2) {
			return;
		}
		else {
			snippet = p[0] + '.' + p[1] + '0';
		}

		$('#customer_height').val(snippet);
	};
			
	new Chooser('gender').setFn('init', ChooserStrategy.singleIcon).init();
	
	new Chooser('skin').
		init().
		setFn('getValue', function(str){
			return ChooserStrategy.getValueByDir(str, '-');
		});
	
	new Chooser('beard_id').
		addObservers('skin', 'gender').
		setFn('changeStatus', ChooserStrategy.beardChangeStatus).
		init();
	
	new Chooser('hair_color_id').init();
	
	new Chooser('hair_style_id').
		addObservers('skin', 'hair_color_id', 'gender').
		setFn('changeStatus', ChooserStrategy.hairStyleChangeStatus).
		init();
	
	new Chooser('glasses_id').init();		
	
	$('#top_size, #bottom_size').change(function(){
		
		var id = $(this).attr('id'),
				value = $(this).find('option:selected').val();
		
		(value === '') ? null : value;
		
		ChooserRegistry.setStatus(id, value);
	});
};

styleForm.populate = function(json){

	var customerData = $.parseJSON(json.data),
			isNew = (customerData.status === 'new')
			style = customerData.Style;

	if (customerData.nick === 'NOT FOUND') {
		$('#gender_female a').click();
		return;
	}			
	
	for (var name in style) {
		ChooserRegistry.setStatus(name, style[name]);
	}
	
	$('#gender_' + style.gender).find('a').click();
	$('#customer_height').data('rangeinput').setValue(style.height);
	$('#customer_weight').data('rangeinput').setValue(style.weight);
	$("img[name='" + style.skin + "']").click();
	$( $('#hair_color_id_chooser img')[style.hair_color_id] ).click();
	$( $('#beard_id_chooser img')[style.beard_id + 1] ).click();
	$( $('#glasses_id_chooser img')[parseInt(style.glasses_id, 10) + 1] ).click();
	$("#top_size option[value='" + style.top_size + "']").attr('selected', 'selected');
	$("#bottom_size option[value='" + style.bottom_size + "']").attr('selected', 'selected');
	
	if (style.is_private)
		$('#is_private').attr('checked', 'checked');
	
	cqlook.loader.hide();
};

styleForm.getData = function(callback){

	if (styleForm.loader)
		cqlook.loader.show();
	
	$.ajax({
		type: 'GET',
		url: '/services/user/get_logged_user',
		dataType: 'json',
		success: callback
	});		
};



String.prototype.removeHtmlQuotes = function() {
	return this.replace(/&quot;/gi,'"');
};

var isUrl = function(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
};

var nullOnEmpty = function(value) {
	if (!value || value === '') value = null;
	return value;
};

var filterCpf = function(value) {
	return value.replace(/\./g,'').replace(/-/,'');
};

var isCpf = function(value) {
	var cpf = filterCpf(value);
	while(cpf.length < 11) cpf = "0"+ cpf;
	
	var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/,
		a = [], b = new Number, c = 11; 
	
	for (i=0; i<11; i++) {
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	
	if ((x = b % 11) < 2) { 
		a[9] = 0 
	} 
	else { 
		a[9] = 11-x 
	}
	b = 0;
	c = 11;
	
	for (y=0; y<10; y++) b += (a[y] * c--);
	if ((x = b % 11) < 2) { 
		a[10] = 0; 
	} 
	else { 
		a[10] = 11-x; 
	}
	
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;
	
	return true;
};

(function($){
	$.fn.inputPlaceHolder = function() {
		var makePlaceHolder = function(index, element) {
			element = $(element);
			if ( ! element.data('placeholder')) {
			element.data('placeholder', {
				original: element.val(),
				isOriginal: function(){
				if (element.data('placeholder').original === element.val()) {
					return true;
				}
				return false;
			},
				resetOriginal: function() {
					element.val(element.data('placeholder').original);
				} 
			});
		}
			
		 var originalValue = element.data('placeholder').original;
			element.focus(function(){
				if (element.val() === originalValue) {
					element.val('');
				}
			});
			element.blur(function(){
				if (element.val().replace(/^\s+|\s+$/g,"")	=== '') {
					element.val(originalValue);
				}
			});	 
		};
		this.each(makePlaceHolder);
	};
})(jQuery);
	
var addZero = function(num) {
	(String(num).length < 2) ? num = String("0" + num) :	num = String(num);
	return num;	 
};

var validateEmail = function(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) {
		return false;
	}
	return true;
};

/*
Masked Input plugin for jQuery
Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function($) {
	var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
	var iPhone = (window.orientation != undefined);

	$.maskInput = {
		//Predefined character definitions
		definitions: {
			'9': "[0-9]",
			'a': "[A-Za-z]",
			'*': "[A-Za-z0-9]"
		}
	};

	$.fn.extend({
		//Helper Function for Caret positioning
		caret: function(begin, end) {
			if (this.length == 0) return;
			if (typeof begin == 'number') {
				end = (typeof end == 'number') ? end : begin;
				return this.each(function() {
					if (this.setSelectionRange) {
						this.focus();
						this.setSelectionRange(begin, end);
					} else if (this.createTextRange) {
						var range = this.createTextRange();
						range.collapse(true);
						range.moveEnd('character', end);
						range.moveStart('character', begin);
						range.select();
					}
				});
			} else {
				if (this[0].setSelectionRange) {
					begin = this[0].selectionStart;
					end = this[0].selectionEnd;
				} else if (document.selection && document.selection.createRange) {
					var range = document.selection.createRange();
					begin = 0 - range.duplicate().moveStart('character', -100000);
					end = begin + range.text.length;
				}
				return { begin: begin, end: end };
			}
		},
		unmask: function() { return this.trigger("unmask"); },
		maskInput: function(mask, settings) {
			if (!mask && this.length > 0) {
				var input = $(this[0]);
				var tests = input.data("tests");
				return $.map(input.data("buffer"), function(c, i) {
					return tests[i] ? c : null;
				}).join('');
			}
			settings = $.extend({
				placeholder: "_",
				completed: null
			}, settings);

			var defs = $.maskInput.definitions;
			var tests = [];
			var partialPosition = mask.length;
			var firstNonMaskPos = null;
			var len = mask.length;

			$.each(mask.split(""), function(i, c) {
				if (c == '?') {
					len--;
					partialPosition = i;
				} else if (defs[c]) {
					tests.push(new RegExp(defs[c]));
					if(firstNonMaskPos==null)
						firstNonMaskPos =	tests.length - 1;
				} else {
					tests.push(null);
				}
			});

			return this.each(function() {
				var input = $(this);
				var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
				var ignore = false;				//Variable for ignoring control keys
				var focusText = input.val();

				input.data("buffer", buffer).data("tests", tests);

				function seekNext(pos) {
					while (++pos <= len && !tests[pos]);
					return pos;
				};

				function shiftL(pos) {
					while (!tests[pos] && --pos >= 0);
					for (var i = pos; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							var j = seekNext(i);
							if (j < len && tests[i].test(buffer[j])) {
								buffer[i] = buffer[j];
							} else
								break;
						}
					}
					writeBuffer();
					input.caret(Math.max(firstNonMaskPos, pos));
				};

				function shiftR(pos) {
					for (var i = pos, c = settings.placeholder; i < len; i++) {
						if (tests[i]) {
							var j = seekNext(i);
							var t = buffer[i];
							buffer[i] = c;
							if (j < len && tests[j].test(t))
								c = t;
							else
								break;
						}
					}
				};

				function keydownEvent(e) {
					var pos = $(this).caret();
					var k = e.keyCode;
					ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

					//delete selection before proceeding
					if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46))
						clearBuffer(pos.begin, pos.end);

					//backspace, delete, and escape get special treatment
					if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete
						shiftL(pos.begin + (k == 46 ? 0 : -1));
						return false;
					} else if (k == 27) {//escape
						input.val(focusText);
						input.caret(0, checkVal());
						return false;
					}
				};

				function keypressEvent(e) {
					if (ignore) {
						ignore = false;
						//Fixes Mac FF bug on backspace
						return (e.keyCode == 8) ? false : null;
					}
					e = e || window.event;
					var k = e.charCode || e.keyCode || e.which;
					var pos = $(this).caret();

					if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
						return true;
					} else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
						var p = seekNext(pos.begin - 1);
						if (p < len) {
							var c = String.fromCharCode(k);
							if (tests[p].test(c)) {
								shiftR(p);
								buffer[p] = c;
								writeBuffer();
								var next = seekNext(p);
								$(this).caret(next);
								if (settings.completed && next == len)
									settings.completed.call(input);
							}
						}
					}
					return false;
				};

				function clearBuffer(start, end) {
					for (var i = start; i < end && i < len; i++) {
						if (tests[i])
							buffer[i] = settings.placeholder;
					}
				};

				function writeBuffer() { return input.val(buffer.join('')).val(); };

				function checkVal(allow) {
					//try to place characters where they belong
					var test = input.val();
					var lastMatch = -1;
					for (var i = 0, pos = 0; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							while (pos++ < test.length) {
								var c = test.charAt(pos - 1);
								if (tests[i].test(c)) {
									buffer[i] = c;
									lastMatch = i;
									break;
								}
							}
							if (pos > test.length)
								break;
						} else if (buffer[i] == test[pos] && i!=partialPosition) {
							pos++;
							lastMatch = i;
						} 
					}
					if (!allow && lastMatch + 1 < partialPosition) {
						input.val("");
						clearBuffer(0, len);
					} else if (allow || lastMatch + 1 >= partialPosition) {
						writeBuffer();
						if (!allow) input.val(input.val().substring(0, lastMatch + 1));
					}
					return (partialPosition ? i : firstNonMaskPos);
				};

				if (!input.attr("readonly"))
					input
					.one("unmask", function() {
						input
							.unbind(".mask")
							.removeData("buffer")
							.removeData("tests");
					})
					.bind("focus.mask", function() {
						focusText = input.val();
						var pos = checkVal();
						writeBuffer();
						setTimeout(function() {
							if (pos == mask.length)
								input.caret(0, pos);
							else
								input.caret(pos);
						}, 0);
					})
					.bind("blur.mask", function() {
						checkVal();
						if (input.val() != focusText)
							input.change();
					})
					.bind("keydown.mask", keydownEvent)
					.bind("keypress.mask", keypressEvent)
					.bind(pasteEventName, function() {
						setTimeout(function() { input.caret(checkVal(true)); }, 0);
					});

				checkVal(); //Perform initial check for existing values
			});
		}
	});
})(jQuery);




