var QUESTION_TEXT = 'text';
var ID_TEXT = 'id_text';
var maxQues = false;
var skipLogicEnabled = false;
var randomizeEnable = false;


function ddd() { console.log.apply(console, arguments); }
function setupDisplay(){
	$("#createSurvey").show();
	$("#__AddSurvey").show();	
	$("#createSurvey #surveyDetails").append($("#survey").clone(true).removeAttr("id"));
}

function determineSkip(skipLogic,skipAllowed){
    if (skipLogic)
        skipLogicEnabled = true;
    else
        skipLogicEnabled = false;
    
    if (!skipLogicEnabled){
        removeSkipHelper();
        $("#removeSkip").hide();
    }
    else
       $("#addSkip").hide()

	if (!skipAllowed)
	    $("#addSkip").hide();
}

function setupTitle(limitQues){

    supported = setupTitleWithoutButton(limitQues);
	//add the Continue Button
	if (supported)
    	$("#surveyTitle").append("<div class='next-row'><div id='createButton' class='blue_button'>Continue >></div></div>");

}
function setupTitleValue(){
	//bring title lable and value to the top
	$("#surveyTitle").append($("#survey *[for=id_title]"));
	$("#surveyTitle").append("<strong> "+document.getElementById("id_title").value+"</strong>");

    //add the title field then hide it
    $("#surveyTitle").append($("#survey #id_title"));
    $("#surveyTitle #id_title").hide()
    // $("#survey #id_title").remove()

	//trim the fat
	$("#survey #id_title").parents("tr").remove()
}

function setupTitleWithoutButton(limitQues){
    if (limitQues){
        maxQues = 10;
        maxQuestionAlert = "Because you have a free membership, you may only have "+maxQues+" questions. Please upgrade to a premium account to remove this limit.";
    }
    else{
        maxQues = 55;
        maxQuestionAlert = "The maximum number of questions allowed is"+maxQues+". Remember its mobile!";
        randomizeEnable = true;
    }
    
    //bring title label and text field up
    var supported = true;
    var warning = "<div class='warning'>We currently do not support this version of your brower. Please upgrade to <a href='http://www.mozilla.com/en-US/firefox/'>Firefox 3</a>.</div>";

	if ($.browser.mozilla && jQuery.browser.version.substr(0,3)!="1.9"){
	    supported = false;
	}
	if (supported){
    	$("#surveyTitle").append($("#survey *[for=id_title]"));
    	$("#surveyTitle").append($("#survey #id_title"));
    	//trim the fat
    	$("#survey #id_title").parents("tr").remove()
	}
	else{
	    $("#surveyTitle").append(warning);
	}
	return supported
}

function setupSurvey(hideSlug){
    $("<tr><th><div class='sectionHeading'>Messages</div></th></tr>").insertBefore($("#survey").find("label[@for=id_description]").parents("tr"))
    $("<tr><th><div class='sectionHeading'>Settings</div></th></tr>").insertBefore($("#survey").find("label[@for=id_closes_0]").parents("tr"))
    $("<tr><th><div class='sectionHeading'>Return Button (optional)</div></th></tr>").insertBefore($("#survey").find("label[@for=id_return_text]").parents("tr"))
    
    if (hideSlug){
        $("#id_slug").parents("tr").hide();
    }
}
function setupQuestions(){	
	// hide all the elements so that we can select certain ones to show
    $("#question").children().hide()
    //show the question types and the buttons initially
    $("#question").find("#id_qtype").show().end().find("*[@for='id_qtype']").show().end().find(".button").show().end().find(".drag").show().end().find(".copy").show().end();
    //prepare the question text by putting it in the question divider
    $("#question").find(".question_div").prepend($("#question").find("#id_text")).prepend($("#question").find("*[@for=id_text]"))
	$("#question").find("#id_required").hide().end().find("label[@for=id_required]").hide().end()

	
	// puts the original name in name_orig for questions and choices
	$(".question").find("#id_text").attr("name_orig","text");
	$(".question").find("#id_next_ques").attr("name_orig","next_ques");
	$(".question").find("#id_randomize_choices").attr("name_orig","randomize_choices");
	
	if (!randomizeEnable)
	    $("#survey_questions").find("input[@name_orig=randomize_choices]").hide().end().find("label[@for=id_randomize_choices]").hide().end();
	

	
	
	// add the question text and corresponding label to its question_div
	$().find(".question").each(function(i){
		// push on text field then the label
		$(this).find(".question_div").prepend($(this).find(".question_table #id_text")).prepend($(this).find(".question_table *[for=id_text]"))		
		qdiv = $(this).find(".question_div");
		$(this).find(".question_table th").each(function(j){
			$(this).children().insertBefore(qdiv);
			$(this).siblings("td").children().insertBefore(qdiv);
		});
		// hides the min-max for non multiple choice
		$(this).find("#id_qtype").each(function(j){
			if (this.value != 'C'){				
			    $(this).parent().find("#id_choice_num_min").hide().end().find("#id_choice_num_max").hide().end().find("label[for=id_choice_num_min]").hide().end().find("label[for=id_choice_num_max]").hide()
			}
		});
		
		//hides the next question for non-multiple choice
		$(this).find("#id_qtype").each(function(j){
			if (this.value != 'C' && this.value != 'S'){				
                // $(this).parent().children("input[@name_orig='next_ques']").hide().end().children("label[@for=id_next_ques]").hide().end().children("input[@name_orig=randomize_choices]").hide().end().children("label[@for=id_randomize_choices]").hide().end();
                $(this).parent().children("input[@name_orig=randomize_choices]").hide().end().children("label[@for=id_randomize_choices]").hide().end();
			}
		});		
	});
    $().find("#survey_questions .question").each(function(i){
       $(this).find(".question_div").children("[@name_orig=text]").each(function(j){
          name = QUESTION_TEXT + "_" + i;
          id = "id_" + name;
          $(this).attr("name",name);
          $(this).attr("id",id); 
       }); 
       
       $(this).children("[@name_orig='next_ques']").each(function(j){
          name = 'next_ques' + "_" + i;
          id = "id_" + name;
          $(this).attr("name",name);
          $(this).attr("id",id); 
       });       
       $(this).children("[@name_orig=randomize_choices]").each(function(j){
          name = 'randomize_choices' + "_" + i;
          id = "id_" + name;
          $(this).attr("name",name);
          $(this).attr("id",id); 
       });       
       
    });


	$(".question > table").remove();
    
    addOrder();
    
	makeQuestionsSortable();
	setupChoices();
}

function addOrder(){
    $("#survey_questions li.question").each(function(i){
        j = i+1;
        if ($(this).find("span.order").length==0)
            $(this).prepend($("<span class='order'/>").html(j+"."));
        else
            $(this).find("span.order").html(j+".");
    });
}

function makeQuestionsSortable(){
    $("#survey_questions").sortable({axis:"y",containment:'#surveyQuestions',placeholder:'space',cursor:'move',handle:'.drag',delay:250,forcePlaceholderSize:true,
                                    update: function(event,ui){
                                        addOrder();
                                    }
    
    });
}

function makeChoicesSortable(){
    $(".question_choices").sortable({axis:"y",placeholder:'space',cursor :'move',handle:'.drag',delay:250,forcePlaceholderSize:true});
}

function setupChoices(){
	// add the question text and corresponding label to its question_div
	$(".choice").find("#id_text").attr("name_orig","text")
	$(".choice").find("#id_next_ques").attr("name_orig","next_ques")
	
	$().find(".choice").each(function(i){
		button = $(this).find(".addChoiceButton");
		$(this).find("th").each(function(j){
			$(this).siblings("td").children().insertAfter(button);
			$(this).children().insertAfter(button);
		});
	});	
	
    $().find("#survey_questions .question").each(function(i){
       $(this).find(".question_choices .choice").each(function(j){
           $(this).children("[@name_orig='text']").each(function(k){
               name = QUESTION_TEXT + "_" + i + '-' + j;
               id = "id_" + name;
               $(this).attr("name",name);
               $(this).attr("id",id); 
               
           });
           $(this).children("[@name_orig='next_ques']").each(function(k){
               name = 'next_ques' + "_" + i + '-' + j;
               id = "id_" + name;
               $(this).attr("name",name);
               $(this).attr("id",id); 
               
           });           
       }); 
    });
	
	
	makeChoicesSortable();
	$(".choice > table").remove();
}

function setDefaults(){
    var d = new Date();
    var offset = 7;
    d.setDate(d.getDate() + offset);
    $("#id_closes_0").attr("value",d.getSlashDate());
    $("#id_closes_1").attr("value",d.getHourMinuteSecond());
    
}

function addKeyBoardHandlers(){
    $("#id_title").keydown(function(e){
       if (e.keyCode == 13){
           e.preventDefault();
           if (!$("#createSurvey").is(":visible")){
               $("#createButton").click(); 
           }
       }
    });

    $(".choice input").keydown(function(e){
        if (e.keyCode == 13){
           e.preventDefault();
           addNew($(this).parents(".choice").children(".addChoiceButton"),"choice",true);
        } 
    });
    
    $(".question input[@name=choice_num_min]").keydown(function(e){
        if (e.keyCode == 13)
            e.preventDefault();
    });
    
    $(".question input[@name=choice_num_max]").keydown(function(e){
        if (e.keyCode == 13)
            e.preventDefault();
    });
    
    $(".question input").not("input[@name=choice_num_min]").not("input[@name=choice_num_max]").keydown(function(e){
        if (e.keyCode == 13){
            e.preventDefault();
            addNew($(this).parents(".question").children(".addQuestionButton"),"question",true);
        } 
    });

}

function addClickHandlers(){
    //for the extra question button at the bottom
	$("#extraAddQuestion").click(function(e){
		e.preventDefault()
		addNew($(),"question",false)
	});
	//for the add question button with each question 
	//to place question after current one
	$(".addQuestionButton").click(function(e){
		e.preventDefault();
		addNew($(this),"question",true);
	});	
	//for the Continue Survey Button
	$("#createButton").click(function(e){
		e.preventDefault()
		//make sure that the survey title is valid
		if($("#survey_form").valid()){
			$(this).hide()                              //get rid of this button
			$("#createSurvey").show()                   // shows the tabs
			$("#__ContinueSurvey").show()               // show the Next Button
			$("#surveyTabs > ul").tabs("disable",1); 	// disable the second tab
			addNew($(),"question",false)                // add a new question
	}
	});
	//for the final submit button
	$("#__AddSurvey").click(function(e){
       $(this).parents("#survey_form").submit() 
	});
    // for the next button
	$("#__ContinueSurvey").click(function(e){
		if($("#survey_form").valid()){
			$("#surveyTabs > ul").tabs("enable",1).tabs('select',1);	
			$("#__ContinueSurvey").hide();
			$("#__AddSurvey").show();
			$("#createSurvey #surveyDetails").append($("#survey").removeAttr("id"))
		}
	});
	
	//for the remove button with each question
	$(".removeQuestionButton").click(function(e){
		e.preventDefault();
		if (confirm("Are you sure you want to delete this question?")){
    		// if there is only one question
    		if ($(this).parent().siblings(".question").length==0){
    		    //removes question ...
    			$(this).parent().remove()
    			// only to add a new blank question
    			$("#survey_questions").append($("#question").clone(true).removeAttr("id"));
    		}
    		else //otherwise just remove
    			$(this).parent().remove()
    		addOrder();		
		}		
	});	
	$(".addChoiceButton").click(function(e){
		e.preventDefault();
		addNew($(this),"choice",true);
	});	
	$(".copy").click(function(e){
	   addNew($(this),"question",true,true); 
	});
	$(".removeChoiceButton").click(function(e){
		e.preventDefault();
		//if there is only one choice
		if ($(this).parent().siblings(".choice").length == 0)
		    //just clear out the value
			$(this).siblings("input[@name_orig='text']").attr("value","")
		else
			$(this).parent().remove();
	});	
	$("select").change(function(){
	    //show all the field
		$(this).parent().find("*").show()
		if (this.value == 'C'){ //show max-min b/c this is select multiple
			$(this).parent().find("#id_choice_num_min").show()
			$(this).parent().find("*[@for=id_choice_num_min]").show()
			$(this).parent().find("#id_choice_num_max").show()
			$(this).parent().find("*[@for=id_choice_num_max]").show()
		}
		else{ //otherwise get rid of select multiple
			$(this).parent().find("#id_choice_num_min").hide()
			$(this).parent().find("*[@for=id_choice_num_min]").hide()
			$(this).parent().find("#id_choice_num_max").hide()
			$(this).parent().find("*[@for=id_choice_num_max]").hide()
		}	

		if (skipLogicEnabled){
		    $(this).parent().find("label[@for='id_next_ques']").show().end().find("input[@name_orig='next_ques']").show();
		}
		else{
		    $(this).parent().find("label[@for='id_next_ques']").hide().end().find("input[@name_orig='next_ques']").hide().attr("value","");
		}


		// if select single or multiple add a choice by default if there isn't already one
		if ((this.value == 'S')||(this.value == 'C')){
			if ($(this).parent().find(".addChoiceButton").length == 0){
				addNew($(this),"choice",false)
			}
    		
    		if (randomizeEnable)
        		$(this).parent().find("label[@for='id_randomize_choices']").show().end().find("input[@name_orig='randomize_choices']").show();
        	else
        		$(this).parent().find("label[@for='id_randomize_choices']").hide().end().find("input[@name_orig='randomize_choices']").hide();
    					
		}
		else{ //remove choices
		 	if ($(this).parent().find(".addChoiceButton").length > 0){
				$(this).parent().find(".choice").remove()
			}
            // $(this).parent().find("label[@for='id_next_ques']").hide().end().find("input[@name_orig='next_ques']").hide().attr("value","");
			$(this).parent().find("label[@for='id_randomize_choices']").hide().end().find("input[@name_orig='randomize_choices']").hide().end();
		}
		// get rid of the default ----- once its changed
		$(this).find("*[value='']").hide()
		$(this).parent(".question").children(".question_div").children("input[@name_orig=text]").focus()
	});
	$("#addSkip").click(function(e){
	    e.preventDefault();
	    $(this).hide();
	    $("#removeSkip").show();
	    addSkipHelper();
	});
	$("#removeSkip").click(function(e){
	    e.preventDefault();
	    $(this).hide();
	    $("#addSkip").show();
	    removeSkipHelper();
	});
	
}

function addSkipHelper(){
    $(".question").find("#id_qtype").each(function(){
       // if (this.value == 'C' || this.value == 'S'){
           $(this).parent().find("label[@for='id_next_ques']").show().end().find("input[@name_orig='next_ques']").show();
       // }
    });
    skipLogicEnabled = true;
}

function removeSkipHelper(){
    $(".question").find("#id_qtype").each(function(){
       // if (this.value == 'C' || this.value == 'S'){
           $(this).parent().find("label[@for='id_next_ques']").hide().end().find("input[@name_orig='next_ques']").hide().attr("value","");
       // }
    });  
    skipLogicEnabled = false;  
}

function addCopy(obj){
    var $objClone = obj.clone(true)
    $objClone = $objClone.find("#id_text").attr("name",name).attr("name_orig",QUESTION_TEXT)
    $objClone = $objClone.attr("id",id).end().find("#id_next_ques").attr("name",'next_ques_'+quesNum).attr("id",'id_next_ques_'+quesNum).end().attr("num",quesNum);
    
    $objClone.insertAfter(obj);
    addOrder();
}

function addNew(c,type,after,copy){
	if (type=="question"){
		var quesNum = $("#survey_questions").find("."+type).length;
		if (maxQues)
    		if (quesNum >= maxQues){
    		    alert(maxQuestionAlert)
    		    return;
    		}
		
		var name = QUESTION_TEXT+'_'+quesNum
		var id = ID_TEXT+'_'+quesNum
		var obj;
		
		NEXT_QUESTION = 'next_ques';
		RANDOM_CHOICES = 'randomize_choices';
		
		if (copy){
		    obj = c.parent().clone(true).removeAttr("id").removeAttr("question_id") 
    		obj = obj.find("input[@name_orig='"+QUESTION_TEXT+"']").attr("name",name)
    		obj = obj.attr("id",id).end()
    		obj = obj.find("input[@name_orig='"+NEXT_QUESTION+"']").attr("name",'next_ques_'+quesNum).attr("id",'id_next_ques_'+quesNum).end().attr("num",quesNum)
    		obj = obj.find("input[@name_orig='"+RANDOM_CHOICES+"']").attr("name","randomize_choices_"+quesNum).attr("id","id_randomize_choices_"+quesNum).end()
    		obj.find("#id_qtype").attr("value",c.parent().find("#id_qtype").attr("value"))
            // choices
            obj.find(".question_choices").find(".choice").each(function(choiceNum){
                name = QUESTION_TEXT+'_'+quesNum+'-'+choiceNum;
    			id = ID_TEXT+'_'+quesNum+'-'+choiceNum;
                $(this).removeAttr("choice_id").find("input[name_orig='text']").attr("id",id).attr("name",name).end().find("input[@name_orig='"+NEXT_QUESTION+"']").attr('id','id_next_ques_'+quesNum+'-'+choiceNum).attr("name",'next_ques_'+quesNum+'-'+choiceNum);
            });
    	}
        else{	
		    obj = $("#"+type).clone(true).removeAttr("id") 
    		obj = obj.find("#id_text").attr("name",name).attr("name_orig",QUESTION_TEXT)
    		obj = obj.attr("id",id).end().find("#id_next_ques").attr("name",'next_ques_'+quesNum).attr("id",'id_next_ques_'+quesNum).end().attr("num",quesNum)
    		obj = obj.find("#id_randomize_choices").attr("name","randomize_choices_"+quesNum).attr("id","id_randomize_choices_"+quesNum).end()
	    }
		    
		if (after){
			obj.insertAfter(c.parent())
		}
		else // just append to the bottom
            $("#survey_questions").append(obj)
        addOrder();
        // $("#survey_questions li.question").each(function(i){
        //     if ($(this).find("span.order").length==0)
        //         $(this).prepend($("<span class='order'/>").html(i+"."));
        //     else
        //         $(this).find("span.order").html(i+".")
        // });
            
        
        obj.find("select").focus();    
        
		makeQuestionsSortable();
	}
	else if (type=="choice"){
		obj =  $("#"+type).clone(true).removeAttr("id").find("#id_text").attr("name_orig",QUESTION_TEXT).end()
		if (after){
			where = c.parents(".choice");
			choiceNum = where.parents(".question_choices").find(".choice").length;
			quesNum = where.parents(".question").attr("num");
			if (!quesNum){
			    quesNum = where.parents(".question").attr("num")
			}
			name = QUESTION_TEXT+'_'+quesNum+'-'+choiceNum;
			id = ID_TEXT+'_'+quesNum+'-'+choiceNum;
			obj.find("input[name_orig='text']").attr("id",id).attr("name",name).end().find("input[name_orig='next_ques']").attr("name",'next_ques_'+quesNum+'-'+choiceNum).attr("id",'id_next_ques_'+quesNum+'-'+choiceNum).end().insertAfter(where);
		}
		else{
			where = c.parents(".question").find(".question_choices");
			choiceNum = where.find(".choice").length;
			quesNum = where.siblings("input[name_orig]").attr("num");
			if (!quesNum){
			    quesNum = where.parents(".question").attr("num")
			}
			name = QUESTION_TEXT+'_'+quesNum+'-'+choiceNum;
			id = ID_TEXT+'_'+quesNum+'-'+choiceNum;
			where.append(obj.find("input[name_orig='text']").attr("id",id).attr("name",name).end().find("input[name_orig='next_ques']").attr("name",'next_ques_'+quesNum+'-'+choiceNum).attr("id",'id_next_ques_'+quesNum+'-'+choiceNum).end());
		}
		obj.find("input[name_orig]").focus()
		
		if (skipLogicEnabled){
		    obj.find("label[@for='id_next_ques']").show().end().find("input[@name_orig='next_ques']").show();
		}
		else{
		    obj.find("label[@for='id_next_ques']").hide().end().find("input[@name_orig='next_ques']").hide().attr("value","");
		}
		
		makeChoicesSortable();
		obj.find("input[@name_orig='text']").focus()    
	}
}
function setupTabs(){
    $("#surveyTabs > ul").tabs();
}
function setupValidations(survey_id) {
	// validate signup form on keyup and submit
	$(".question input[@name_orig=text]").addClass("required");
	$(".choice input[@name_orig=text]").addClass("required");
	$("#id_title").addClass("required");
    $(".datetime .vDateField").addClass("required dateHAS");
    $(".datetime .vTimeField").addClass("required time");
    $("input[@name_orig='next_ques']").addClass("digits")
    // $("#id_return_link").addClass("url");
	
    // if (checkTitle)
    //     rules = {}
    // else
    survey_check_url = "/survey/check"
    if (survey_id){
        survey_check_url += "/" + survey_id + "/"
    }
    rules = {
                slug:{
                        remote: survey_check_url
                },
                description:{
                    maxlength: 100
                },
                thank_you:{
                    maxlength: 100
                }
            }
            
	$("#survey_form").validate({
	    rules: rules,
        messages: {
                slug: {
                        remote: jQuery.format("A short code {0} already exists") 
                }
        },
        
		debug: true,
	
		// CALLBACKS BABY
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			var err = element.siblings(".error");
            
            var detailsTab = element.parents("#surveyDetails")
            var questionsTab = element.parents("#surveyQuestions")
            if (detailsTab.length>0){
                var tabs = $("#surveyTabs ul")
                if (!detailsTab.is(":visible"))
                    if (tabs.children(".detailsError").length==0)
                        $("<span class='tabExtra detailsError error'>Details contain errors</span>").appendTo(tabs)
            }
            // if (questionsTab.length>0){
            //     var tabs = $("#surveyTabs ul")
            //     if (!questionsTab.is(":visible"))
            //         if (tabs.children(".questionError").length==0)
            //             $("<div class='tabExtra questionError error'>Questions contain errors</div>").appendTo(tabs)
            // }
                

            var visible = element.is(":visible") && element.parent().is(":visible");            
            if (!visible){
                error.insertAfter(element.parent())
                return
            }
            
			if (err.length==0){
				error.insertAfter(element);
			}
			else{
				error.appendTo(err);
			}
		},
		submitHandler: function(form){
            submitHelper(form)
		    //finally submit
            form.submit();
            //hack for FF ok
            // $("#extraAddQuestion").click()
		}
	});
}

function submitHelper(form){
    var DELIM="__";
    var QTAG = "question"
    var CTAG = "choice"
    
    //prepare questions and choices for submission by re-nameing, etc
    // $("#survey_questions").find(".question").find("input[name_orig='text']").attr("name",QUESTION_TEXT).end().each(function(i){
    //     $(this).find(".choice").each(function(j){
    //     // append the question number to the choice
    //         $(this).find("input[name_orig]").each(function(i){
    //             var name_orig = $(this).attr("name_orig");
    //             $(this).attr("name",name_orig);
    //         });
    //         
    //         attr("name","text");
    //         $(this).find("input[name_orig='next_ques']").attr("name","next_ques");
    //     });
    // }); 
    
    $("#survey_questions").find("input[name_orig]").each(function(i){
        var name_orig = $(this).attr("name_orig");
        $(this).attr("name",name_orig);
    });
    
    $("#survey_questions").find(".question").each(function(i){
        question_id = $(this).attr("question_id");

        $(this).find(".choice").each(function(j){
            choice_id = $(this).attr("choice_id");
            $(this).find("*[name]").each(function(k){
                eleName = CTAG + DELIM + $(this).attr("name") + DELIM + i + DELIM + j;
                if (choice_id){
                    eleName += DELIM + choice_id;
                }
                $(this).attr("name",eleName);
            });    
        });
        
        function questionPrep(j,ele){
            eleName = QTAG + DELIM + ele.attr("name") +DELIM+i;
            if (question_id){
                eleName += DELIM + question_id;
            }
            ele.attr("name",eleName);
        }
        $(this).children("*[name]").each(function(i){questionPrep(i,$(this))});
        $(this).find(".question_div").children("*[name]").each(function(i){questionPrep(i,$(this))});
    });
}