$(document).ready(function() {
	$("#factoryMainWrap").cssGenerator();
});

(function ($) {

	var base = null;
	var generator = null;

	$.fn.cssGenerator = function() {
		base = $(this);
		
		generator = new Generator();
		generator.init();
		
		$("a.factoryMenuHead, a.factoryHelp").each(function() {
		    builder = new QueryBuilder($(this));
		});
		
		applyBuilder = new QueryBuilder($("a.factoryApply"), $("link[type=text/css][href$=Preview.ashx]"));
	};
	
	function Generator() {
		this.init = function() {
		
		    base.find("input")
		        .keypress(function(e) {
		            return (e.which != 13)
		        });
					
			base.find("input.color-field")
			    .focus(function() {
					$("#color-picker").insertAfter($(this));
					var fb = $.farbtastic($("#color-picker"), $(this));
					fb.linkTo($(this));
					$("#color-picker").show();
				})
				.blur(function() {
					$("#color-picker").hide();
				})
				.validHex()
                .keyup(function() {
                    $(this).validHex();
                })
                .each(function(){
                    $(this).css("background-color", $(this).val());
                });
                
            base.find("input.opacity-field")
                .validPercentage()
                .keyup(function() {
                    $(this).validPercentage();
                });
                
            base.find("input.font-size-field, input.corner-radius-field, input.border-field")
                .validCssLength()
                .focus(function() {
                    $(this).validCssLength();
                })
                .blur(function() {
                    $(this).validCssLength();
                });
			
			base.find("div.texture-field")
			    .click(function() {
					var picker = $("#texture-picker");
					
					if (picker.visibleByCSS()) {
						picker.hide();
					}
					else {
						picker.insertAfter($(this));
						picker.show();
					}
				});
			
			base.find(".factory-theme-group-header")
			    .initializeGroupHeaders();
			    
			base.find("input[type=button]")
			    .setHover();
			
			base.find("input[type=text], select, textarea")
			    .setActive();
			    
			$("#texture-picker > ul > li > a")
			    .selectTexture();
		};	
	};
	
	function QueryBuilder(element, applyElement) {
		var instance = this;
		
		this.element = element;
		this.applyElement = (applyElement == null) ? element : applyElement;;
		this.address = (applyElement == null) ? element.attr("href") : "Preview.ashx";
		this.query = "?";
		
		this.element.click(function() {
		    instance.clearAddress();
			instance.grabParameters();
			instance.apply();
			//return false;
		});
		
		this.grabParameters = function() {
			$("form input, form select, form textarea").filter("[id^=" + THEME_FIELDS_PREFIX + "]")
				.each(function() {
					instance.query += escape($(this).attr("id").substring(1, $(this).attr("id").length));
					instance.query += "=";
					instance.query += escape($(this).val());
					instance.query += "&";
				});
				
			instance.query = instance.query.substring(0, instance.query.length - 1);
		};
		
		this.apply = function() {
		    instance.applyElement.attr("href", instance.address + instance.query);
	    };
	    
	    this.clearAddress = function() {
	        var applyURL = instance.applyElement.attr("href");
	        var index = applyURL.indexOf("?");
	        
	        if (index != -1) {
                instance.applyElement.attr("href", applyURL.substring(0, index));
	        }
	        
	        instance.query = "?";
	    };
	};
	
	$.fn.setHover = function() {
		return this.each(function() {
			$(this)
				.hover(
					function() { $(this).addClass("ui-state-hover"); },
					function() { $(this).removeClass("ui-state-hover"); }
				)
				.mousedown(
					function() { $(this).addClass("ui-state-active"); }
				)
				.mouseup(
					function() { $(this).removeClass("ui-state-active"); }
				)
		});
	};
	
	$.fn.setActive = function() {
		return this.each(function() {
			$(this).focus(function() {
				$(this).addClass("state-active");
				
				$("#texture-picker").hide();
			})
			.blur(function() {
				$(this).removeClass("state-active");
			});
		});
	};
	
	$.fn.initializeGroupHeaders = function() {
		return this.each(function() {
			$(this)
				.click(function() {
					var icon = $(this).find("span.ui-icon");
					
					if ($(this).next().is(":visible")) {
						$(this).next().slideUp();
						icon.removeClass("ui-icon-triangle-1-s");
						icon.addClass("ui-icon-triangle-1-e");
					}
					else {
						$(this).next().slideDown();
						icon.removeClass("ui-icon-triangle-1-e");
						icon.addClass("ui-icon-triangle-1-s");
					}
				})
				.hover(function() {
						$(this).addClass("state-hover");
					},
					function() {
						$(this).removeClass("state-hover");
					}
				);
		});
	};
	
	$.fn.visibleByCSS = function() {
		return $(this).css("display") == "block";
	};
	
	$.fn.selectTexture = function() {
		return this.each(function() {
			$(this).click(function() {
				var textureView = $(this).parent().parent().parent().prev();
				textureView.attr("class", "texture-field");
				textureView.addClass($(this).parent().attr("class"));
				textureView.parent().find("input[id$=.texture]").val($(this).parent().getBackgroundImage());
				$("#texture-picker").hide();
				return false;
			});
		});
	};
	
	$.fn.getBackgroundImage = function() {
	    var imagePath = $(this).css("background-image");
	    
	    if (imagePath == "none") return "";
	    
	    var value = imagePath.substring(imagePath.lastIndexOf("/") + 1);
	    
	    return value.replace(/[\)\"]/g, '');
	};
	
    $.fn.validHex = function() {
        return this.each(function() {    
            var value = $(this).val();
            value = value.replace(/[^#a-fA-F0-9]/g, '');
            if (value.match(/#/g) && value.match(/#/g).length > 1) value = value.replace(/#/g, '');
            if (value.indexOf('#') == -1) value = '#'+value;
            if (value.length > 7) value = value.substr(0,7);
            $(this).val(value);
         });
    }; 
    
    $.fn.validPercentage = function() {
        return this.each(function() {
            var value = $(this).val();
            value = value.replace(/[^0-9]/g, '');
            if (value.length > 3 && value.substr(0,3) == "100") value = value.substr(0,3);
            if (value.length > 2 && value != "100") value = value.substr(0,2);
            $(this).val(value);
        });
    };
    
    $.fn.validCssLength = function() {
        return this.each(function() {
            var value = $(this).val();
            if (!value.match(/^\s*(((\d*(\.\d+))|(\d*)){1})\s{0,1}(((em)|(ex)|(px)|(%)|(in)|(cm)|(mm)|(pt)|(pc)){0,1})\s*$/g)) {
                if (parseInt(value, 10) == NaN) value = "0px";
            }
            $(this).val(value);
        });
    };

})(jQuery);
