var createList = window.createList || {};
    //list autocompete url
    createList.listsAutocompleteUrl = Listiki.baseUrl + "search/lists";
    //item autocompete url
    createList.itemsAutocompleteUrl = Listiki.baseUrl + "search/items";
    //tags autocomplete url
    createList.tagsAutocompleteUrl = Listiki.baseUrl + "search/tags";
    
    createList.title = '';
    
    createList.submit = false;

    createList.init =  function(){
        //init autocomplete and delete for the first item input
        createList.initItem($(".form-list-item"));
		$(".form-list-item:first a").hide();
		$(".form-list-item a.create-list-delete-item").click(function(e){
            e.preventDefault();
            var size = $("ul.items-to-add .form-list-item:not(.deleting)").size();
            if (size<2){
                $(".form-list-item:first a").fadeOut("slow");
                return;
            }
            $(this).parent().addClass("deleting");
            $(this).parent().fadeOut('slow',function(){
                $(this).remove();
                createList.redefineItemsPositions();
            });
        });
        //init tags functionality (autocomplete etc.)
        createList.initTags();
        //init list title functionality (autocomplete etc.)
        createList.initListTitle();
		
		createList.initForm();
		
		createList.initTweet();
		
        //making list items sortable
        $("ul.items-to-add").sortable({
            stop : function(event,ui){
                createList.redefineItemsPositions();
            }
        });
		
		createList.initCheckboxes();
		
        //adding add item functionality
		$("#add-list-item").click(function(e){
			e.preventDefault();
			$(".form-list-item:first a").show();
			var totalItems = $("input.list-item").size();
			if (totalItems >=5){
				return;
			}
			var $newItem = $(".form-list-item:last").clone(true);
			$newItem.find("input").removeClass("amazon-product");
			$newItem.find("input").attr("value","");
			$newItem.find("span.number").text(++totalItems);
			$newItem.insertAfter(".form-list-item:last");
			createList.initItem($(".form-list-item:last"));
		})
		
		$('#create-list-form .cancel').click(function(e){
			//alert(history.length);
			if(history.length > 1) {
				history.back();
			} else {
				window.location.href = Listiki.baseUrl;
			}
		});
    }

    //after items have  been sorted or some items were deleted
    //we need to rearrange items. This method implements this functionality
    createList.redefineItemsPositions = function(){
		$("ul.items-to-add .form-list-item").each(function(index,obj){
			$(obj).find("span.number").text(index+1);
		});
    }

    //after new item input has benn added we need to init autocomplete and item delete button events
    //this function implements this functionality
    createList.initItem = function($newItem){
        
		$newItem.find("input.list-item").focus(function(){
			listikiAutocomplete.addItem($(this));
			if (this.value == this.defaultValue){
				this.value = '';
				$(this).addClass("black");
			}
		}).each(function(i,obj){this.value=this.defaultValue});
		$newItem.find("input.list-item").blur(function(){
			if (this.value == ''){
				this.value = this.defaultValue;
				$(this).removeClass('black');
			}
			setTimeout(function(){
				$(this).unautocomplete();
			},2000);
		});
		
		$newItem.find("input.item-url").focus(function(){
			
			if (this.value == this.defaultValue){
				this.value = '';
				$(this).addClass("black");
			}
		}).each(function(i,obj){this.value=this.defaultValue});
		$newItem.find("input.item-url").blur(function(){
			if (this.value == ''){
				this.value = this.defaultValue;
				$(this).removeClass('black');
			}
		});
		
        //initializing item autocomlete to the item input field
    }

    createList.initTags = function(){
        listikiAutocomplete.add($("#list-tags"),createList.tagsAutocompleteUrl,true);
        $("#list-tags").tagEditor({
            confirmRemoval: false
        });
		
		$("#list-tags").click(function(e){
			if (this.value == this.defaultValue){
				this.value = '';
			}
		});
    }

    createList.initListTitle = function(){
        listikiAutocomplete.add($("#list-name"),createList.listsAutocompleteUrl);
		
		$("#list-name").click(function(){
			if ( this.value == this.defaultValue){
			this.value = '';
			$(this).addClass("black");
			}
		});
		$("#list-name").blur(function(){
			if (this.value == ''){
			this.value = this.defaultValue;
			$(this).removeClass("black");
			}
		});
    }
    
    createList.initForm = function(){
    	$("#create-list").appendTo("body");
    	$("#create-list").css({position:"absolute"});
    	
    	$('#fader_bg').click(function(){
    		createList.submit = false;
    		$("#create-list").hide();
    	});    	
    	   	
    	
    	$("#create-list a.create-list-confirm").click(function(){    		
    		createList.submit = true;
    		
    		$("#create-list-form").submit();
    		$('#fader_bg').click();
    		
    		return false;
    	})
    	
		$("#create-list-form").submit(function(){
			
			if(createList.submit) {
				createList.submit = false;
			} else {
				
				var list_title = $("#list-name").get(0);
				if (list_title.value == list_title.defaultValue){
					//list_title.value = '';
					if($('.title-error').length)return false;
					$('<div class="title-error">Enter list title</div>').insertAfter($(list_title).parent());
					return false;
				}
				$('.title-error').remove();
				
				//search coincidence
				
				
			    
			    createList.title = list_title.value;
			    
				$.ajax({
					url : Listiki.baseUrl + "list/coincidence",
					type : "post",
					data: {title: list_title.value},
					dataType: "json",
					success : function(data){
						$('.create-list-items ul').html('');
						createList.submit = true;				
						
						if(data.length <= 0) {							
							$("#create-list-form").submit();
							
							return;
						} else {
							
							
					       
							
							
							$('#fader_bg').click(function(){
						        $("#create-list").hide();
						    });
						    	
						    
						    $("a.cancel").click(function(){
						    	$('#fader_bg').click();
						    	return false;
						    });
							
							$.each(data, function(i, item) {							
								
							
								var _a = $('<a/>')
									.attr('href', Listiki.baseUrl + item.custom_route)
									.append(item.title);
									
								var _ul = $('<li/>')
												.append(_a)
												.append("with " + item.item_counts + ((item.item_counts <= 1) ? " item" : " items"));
								
								$('.create-list-items ul').append(_ul);															
								
							})
							
							showFader();
							$('#create-list').show();
							
							var topOffset = ($(window).height() - $("#create-list").height() ) /2;
							var leftOffset = ($(window).width() - $("#create-list").width() ) /2;
							
							$("#create-list").css({
					            top: topOffset + $(window).scrollTop() + "px",
					            left: leftOffset + "px"
					        });
							
							/*var _a = $('<a/>')
								.append(createList.title)
								.attr('href', '#')
								.click(function(){
									$('#fader_bg').click();
						    		$("#create-list-form").submit();
						    		
									return false;
								})
						
							var _ul = $('<li/>')
											.append(_a)
											.append("your list");
							
							$('.create-list-items ul').append(_ul);*/
						}
										
					}
				})
				
				return false;				
			}
			
			/*
			var list_tags = $("#list-tags").get(0);
			if (list_tags.value == list_tags.defaultValue){
			list_tags.value = '';
			}
			*/
			
			/*
				
				HERE GOES ADD ITEMS ON CREATE LIST
				
			$("input.list-item").each(function(i,obj){
				if(obj.value=='')obj.value = obj.defaultValue;
				if (obj.value == obj.defaultValue){
					$(obj).addClass('title-item-err');
				}else{
					$(obj).removeClass('title-item-err');
				}
			});
			if($('.title-item-err').length)return false;
			$(this).find("input.list-item").each(function(i,obj){
				//var link = $(obj).attr("rel");
				/*
				if ($(obj).hasClass("amazon-product") && link){
					$(obj).attr("value", $(obj).val() + " (amazon product [link]"+ link +"[/link] )" );
				}
				*
				
				/* items url *
					var item_url = $(obj).next();
					if(item_url.val() != item_url.defaultValue){
						if(item_url.val().indexOf('http')<0&&item_url.val().indexOf('ftp')<0){
							item_url.val('http://'+item_url.val());
						}
						if(!testUrl(item_url.val())){
							if(!item_url.next().hasClass('url-error'))
								$(' <span class="url-error">You must specify correct item url</span>').insertAfter(item_url);
							//return false;
						}else{
							item_url.parent().find('span.url-error').remove();
						}
					}
				/* end| items url *
			});
			if($('.url-error').length) return false;
			//check errors first, and after go to this
			$(this).find("input.list-item").each(function(i,obj){
				var item_url = $(obj).next();
				if ( (item_url.val() != item_url.attr("defaultValue") ) && item_url.val() != ""){
					$(obj).attr("value", $(obj).val() + " (item_url [link]"+ item_url.val() +"[/link] )" );
				}
				$(obj).removeAttr("maxlength");
			});
			$("input.item-url").removeAttr("name");
			
			
			
			*/
		});
		//return false;
    }

    createList.initCheckboxes = function(){
		$("#tweet-text,#password-value").hide();
		$("#tweet").change(function(){
			if (this.checked){
			if ($("#pwd").get(0).checked){
				this.checked = false;
			}else{
				$("#tweet-text").show();
			}
			}else{
			$("#tweet-text").hide();
			}
		});
		$("#pwd").change(function(){
			if (this.checked){
			$("#password-value").show();
			$("#tweet").get(0).previousState = $("#tweet").get(0).checked;
			$("#tweet").attr("checked","");
			$("#tweet-text").hide();
			}else{
			$("#password-value").hide();
			$("#tweet").get(0).checked = $("#tweet").get(0).previousState;
			if ($("#tweet").get(0).previousState){
				$("#tweet-text").show();
			}
			
			}
		});
    }
    
    createList.initTweet = function(){
		$("#list-name").keyup(function(){
			var val = $(this).val();
			$("#tweet-list-name").text(val);
		});
		
		
		
		/*
		gigya.services.socialize.getUserInfo(GigyaConf,
			{
				callback: function(response){
					if(response.user!=undefined){
						if (response.user.loginProvider == 'facebook'){
							$("label[for=tweet]").text("Share it");
						}
					}
				}
			}
		);
		*/
    }
	
$(document).ready(function(){
	var value = $('#create-list-form input[name="list-name"]').attr('value') || '';
	var initLength = Math.max((value ? (255 - value.length) : 255),0);
	$('#list-name-counter').html(initLength.toString());
	
	$('#create-list-form input[name="list-name"]').keyup(function(){
		var value = $(this).attr('value') || '';
		var lengthToGo = Math.max((255 - value.length),0);
		$('#list-name-counter').html(lengthToGo.toString());
	});
});	
