/***
 ** CourseBuilder Specific JS
 ***/

// Create new SocratED.CoursePage Namespace
if (SocratED.CoursePage == null || typeof(SocratED.CoursePage) != "object") { SocratED.CoursePage = new Object(); }
SocratED.CoursePage = {

  selectPayMode : function (have_acct){
	if(have_acct == "1" && $("#zoom #payment_signup_form").is(":visible")){
	    $("#zoom #payment_signup_form").fadeOut("normal",function(){ $("#zoom #payment_login_form").fadeIn(); });
	}
        else if (have_acct == "0" && $("#zoom #payment_login_form").is(":visible")){
            $("#zoom #payment_login_form").fadeOut("normal",function(){$("#zoom #payment_signup_form").fadeIn(); });
	}
  },

  purchase_in_process : false,
  purchase : function(){

	// Don't do purchase again if we're currently processing
	if (SocratED.CoursePage.purchase_in_process) return false;
        // Don't Allow Blank Login Email
        if ($("#zoom form #order_do_login").val() == "1" && 
            ($.trim($("#zoom form #user_session_email").val()) == "" || ($.trim($("#zoom form #user_session_email").val())==$.trim($("#zoom form #user_session_email").attr('title'))))){
            alert('Please fill in the email field so we can generate and email you a password.');
            return false;
        }
        // Don't allow blank login password field
        if ($("#zoom form #order_do_login").val() == "1" && $.trim($("#zoom form #user_session_password").val()) == ""){
            alert('Please fill in the password field.');
            return false;
        }
        // Don't allow blank signup name field
        if ($("#zoom form #order_do_login").val() == "0" &&
            ($.trim($("#zoom form #user_name").val()) == "" || ($.trim($("#zoom form #user_name").val())==$.trim($("#zoom form #user_name").attr('title'))))){
            alert('Please fill in the name field so you can participate in exercise and post comments.');
            return false;
	}
	// Don't allow blank signup email field
	if ($("#zoom form #order_do_login").val() == "0" &&
            ($.trim($("#zoom form #user_email").val()) == "" || ($.trim($("#zoom form #user_email").val())==$.trim($("#zoom form #user_email").attr('title'))))){
            alert('Please fill in the email field so we can generate and email you a password.');
            return false;
	}
        // Don't allow blank card name
        if ($.trim($("#zoom form #order_card_name").val()) == "" || ($.trim($("#zoom form #order_card_name").val())==$.trim($("#zoom form #order_card_name").attr('title')))){
            alert('Please fill in the name that appears on your credit card.');
            return false;
        }
        // Don't allow blank credit card number
        if ($.trim($("#zoom form #order_card_number").val()) == "" || ($.trim($("#zoom form #order_card_number").val())==$.trim($("#zoom form #order_card_number").attr('title')))){
            alert('Please fill in your credit card number.');
            return false;
        }
        // Don't allow blank cvv
        if ($.trim($("#zoom form #order_card_verification").val()) == "" || ($.trim($("#zoom form #order_card_verification").val())==$.trim($("#zoom form #order_card_verification").attr('title')))){
            alert('Please fill in your credit card id (CVV).');
            return false;
        }

	// Disable Purchase Button
	SocratED.CoursePage.purchase_in_process = true;
	$("#zoom .purchase_button").fadeTo('normal',.7);
	$("#zoom .purchase_button").text('Processing...');
	$("#zoom .purchase_button").addClass('no_hover');

	$.ajax({
                type: "POST",
		    cache: false,
		    url: $('#zoom form').attr('action'),
		    data: $('#zoom form').serialize() + "&_method=POST",
		    complete: function(xhr, textStatus) {
		    // Success 
		    if (xhr.status == "200") {
                        $('#zoom .pay2_form').html(xhr.responseText);
                        SocratED.CoursePage.purchase_in_process = false;
                        $("#zoom .purchase_button").fadeTo('normal',1);
                        $("#zoom .purchase_button").text("Continue Course");
                        $("#zoom .purchase_button").removeClass('no_hover');
		    }
		    // Error
		    else {
			$('#zoom .pay2_form').html(xhr.responseText);
			// Reenable Purchase Button
			SocratED.CoursePage.purchase_in_process = false;
		    }
		}
	    });
    },
  
    registerConversion : function(amount){

        // Only register conversions in production
        if (SocratED.RAILS_ENV != "production") return;

	// With Performable ** PERFORMABLE HEADER JS MUST BE IN PAGE HEADER - ONLY ON SITE RIGHT NOW **
	_paq.push(["trackConversion", {id: "5trgnT7fR9Tn", domain: "learning.socrated.com", value: amount}]);

    },

    // Make Buy Button Work (cant init till popup loads)
    initPay1Window : function(){
        if(!$('#zoom .pay1_button').length){ 
	    setTimeout("SocratED.CoursePage.initPay1Window()",200);
            return;
	}
        else {
  	    $('.pay1_button').fancyZoom({directory: '/images/fancyzoom', closeOnClick: false});
        }
    }

}

// Create new SocratED.CourseBuilder Namespace
if (SocratED.CourseBuilder == null || typeof(SocratED.CourseBuilder) != "object") { SocratED.CourseBuilder = new Object(); }
SocratED.CourseBuilder = {

  changePublished : function(publish_select){
    if ($(publish_select).val() == "true"){
	$("#public_status").slideDown();
        $("#landing_page").slideUp();
    }
    else {
        $("#public_status").slideUp();
        $("#landing_page").slideDown();
    }
    // Update all publish drop downs so the last one has hte right value
    $(".publish_select").val($(publish_select).val());
  },

  deleteItem : function(item_el){
    item_ids = SocratED.CourseBuilder.findItemIds(item_el);
    item_id = item_ids['item'];
    chapter_id = item_ids['chapter'];
    item = $("#content_item_"+chapter_id+"_"+item_id);

    if (!confirm("Are you sure you want to delete this content item? " +
		 "It will be permanently deleted.")){
	return 0;
    }

    // If this is not a new (unsaved) item
    if (!$(item).hasClass("new")){
        // Mark Deleted and submit form
        $("#course_chapters_attributes_"+item_ids['chapter']+"_content_items_attributes_"+item_ids['item']+"__delete").val(1);
        document.course_form.submit();
    }
    // New (unsaved) Item
    else {

        // Slide Up & Remove Item
        $(item).slideUp(function(){
 	    $(item).remove();

  	    // Renumber all the items starting with the first item after this one
	    $("#chapter_"+chapter_id).find(".content_item").each(function(){
                chapter_iter = parseInt($(this).attr("id").split("_")[2]);
                item_iter = parseInt($(this).attr("id").split("_")[3]);
                if (item_iter > item_id){
                    SocratED.CourseBuilder.renumberItem(this, chapter_iter, item_iter-1);
                }
	    });
	});

    }
    
  },

  deleteChapter : function(chapter_el){
     chapter_id = SocratED.CourseBuilder.findChapterId(chapter_el);
     chapter = $("#chapter_"+chapter_id);
     if (!confirm("Are you sure you want to delete this chapter? " + 
                 "This chapter and all its content items will be permanently deleted.")){
	 return 0;
     }

     // If this is not a new (unsaved) chapter
     if (!$(chapter).hasClass("new")){
         $("#course_chapters_attributes_"+chapter_id+"__delete").val(1);
         document.course_form.submit();
     }
     // New (unsaved) chapter
     else {
	 // Slide Up & Remove chapter
	 $(chapter).slideUp(function(){
	     $(chapter).remove();
	     // Renumber all the chapters starting with chapter_id
	     $("#chapters .chapter").each(function(){
	         chapter_iter = parseInt($(this).attr("id").match(/_(\d*)/i)[1]);
	         if (chapter_iter > chapter_id){
	             SocratED.CourseBuilder.renumberChapter(this, chapter_iter-1);
		 }
	     });
	 });
     }

  },

  addChapter : function(chapter_el){

     // Insert at bottom
     if (typeof chapter_el == "undefined"){
         before_chapter_id = parseInt($("#chapters .chapter:last").attr("id").match(/_(\d*)/i)[1]);
     }
     // Insert before before_chapter_id chapter (before_chapter_id becomes new chapter id)
     else {
	 before_chapter_id = SocratED.CourseBuilder.findChapterId(chapter_el);
     }

     $.fn.reverse = [].reverse;
     // Renumber all the chapters starting with before_chapter_id
     $("#chapters .chapter").reverse().each(function(){
       chapter_iter = parseInt($(this).attr("id").match(/_(\d*)/i)[1]);
       if (chapter_iter >= before_chapter_id){
	   SocratED.CourseBuilder.renumberChapter(this, chapter_iter+1);
       }
     });

     // Clone the chapter from the template, renumber it, insert it before
     cht = $("#chapters .chapter.template").clone();
     SocratED.CourseBuilder.renumberChapter(cht,before_chapter_id);
     $(cht).removeClass("template").hide();
     $(cht).find(".content_item").each(function(){
	$(this).removeClass("template") // remove from children as well
     });
     $(cht).insertBefore("#chapter_"+(parseInt(before_chapter_id)+1)).slideDown();
     SocratED.CourseBuilder.renumberChapterPostAdd(cht,before_chapter_id);

     // Enable Viddler Link                                                                                                                                                                             
     $("#chapter_" + before_chapter_id  + " .viddler_link").fancyZoom({directory: "/images/fancyzoom", closeOnClick: false});

  },

  // Clone a chapter and renumber it
  renumberChapter : function(chapterObject, new_id){

        old_id = $(chapterObject).attr("id").match(/_(\d*)/i)[1];
        // Renumber Chapter's Content Items
        $(chapterObject).find(".content_item").each(function(){
            SocratED.CourseBuilder.renumberItem(this, new_id, $(this).attr("id").split("_")[3]);
            SocratED.CourseBuilder.renumberItemPostAdd(this, new_id, $(this).attr("id").split("_")[3]);
	});
        // Store Old Values (because new chapters values will get erased below)
        old_values = new Array();
        $(chapterObject).find("input, textarea, select").each(function(iter){
		old_values[iter] = $(this).val();
	});
	// Renumber Chapter
	$(chapterObject).html(
		    $(chapterObject)
		    .html()
		    .replace(new RegExp("course_chapters_attributes_"+old_id,"gi"),"course_chapters_attributes_"+new_id)
		    .replace(new RegExp("course.chapters_attributes.."+old_id+"\]","gi"),"course\[chapters_attributes\]\["+new_id+"\]")
		    .replace(new RegExp("Chapter "+(parseInt(old_id)+1),"gi"),"Chapter "+(parseInt(new_id)+1))
		    .replace(new RegExp("content_item_"+old_id+"_","gi"),"content_item_"+new_id+"_")
		    ).attr("id","chapter_"+new_id);
        // Plug old values back in
        $(chapterObject).find("input, textarea, select").each(function(iter){
                $(this).val(old_values[iter]);
	});
	// Change ID of Chapter
	$("#course_chapters_attributes_"+old_id+"_id").attr("name","course[chapters_attributes]["+new_id+"][id]");
        $("#course_chapters_attributes_"+old_id+"_id").attr("id","course_chapters_attributes_"+new_id+"_id");
        SocratED.CourseBuilder.renumberChapterPostAdd(chapterObject, new_id);

  },

  // Finish Renumbering a chapter After an item is added to the page 
  renumberChapterPostAdd : function(chapterObject, new_id){
        // Change Position Number
	$("#course_chapters_attributes_"+new_id+"_position").val(new_id);
        // Change ID
        $(chapterObject).attr("id","chapter_"+new_id);
  },

  addItem : function(item_el, bottom){

	// Insert at bottom
        if (typeof bottom != "undefined" && bottom){
            before_chapter_id = SocratED.CourseBuilder.findChapterId(item_el);
            if ($("#chapter_"+before_chapter_id).find(".content_item:last").length>0){
              after_item_id = parseInt($("#chapter_"+before_chapter_id).find(".content_item:last").attr("id").split("_")[3]);
              new_item_id = after_item_id + 1;
	    }
            else {
	      new_item_id = 0;
	    }
            // Clone the item from the template, renumber it, insert it before
            cht = $(".content_item.template").clone();
            SocratED.CourseBuilder.renumberItem(cht,before_chapter_id,new_item_id);
            $(cht).removeClass("template").hide().insertBefore($("#chapter_"+before_chapter_id).find(".add_item_box")).slideDown();
            SocratED.CourseBuilder.renumberItemPostAdd(cht,before_chapter_id,new_item_id);
	}
	// Insert before before_item_id item (before_item_id becomes new item id)
        else {
	    item_ids = SocratED.CourseBuilder.findItemIds(item_el);
            before_item_id = item_ids['item'];
            before_chapter_id = item_ids['chapter'];
   	    $.fn.reverse = [].reverse;
	    // Renumber all the items starting with before_item_id
	    $("#chapter_"+before_chapter_id).find(".content_item").reverse().each(function(){
                chapter_iter = parseInt($(this).attr("id").split("_")[2]);  
		item_iter = parseInt($(this).attr("id").split("_")[3]);
		if (item_iter >= before_item_id){
		    SocratED.CourseBuilder.renumberItem(this, chapter_iter, item_iter+1);
		}
  	    });
            // Clone the item from the template, renumber it, insert it before
            cht = $(".content_item.template").clone();
            SocratED.CourseBuilder.renumberItem(cht,before_chapter_id,before_item_id); 
   	    $(cht).removeClass("template").hide().insertBefore("#content_item_"+before_chapter_id+"_"+(before_item_id+1)).slideDown();
	    SocratED.CourseBuilder.renumberItemPostAdd(cht,before_chapter_id,before_item_id);
	}
       
        // Enable Viddler Link
	$('#' + $(cht).attr("id") + ' .viddler_link').fancyZoom({directory: "/images/fancyzoom", closeOnClick: false});
 
  },

  // Renumber a Content Item
  renumberItem : function(itemObject, new_chapter_id, new_item_id){

        old_chapter_id = parseInt($(itemObject).attr("id").split("_")[2]);
        old_item_id = parseInt($(itemObject).attr("id").split("_")[3]);
        // Save Old Value (bc browser for some reason erases them)
        old_values = new Array();
        $(itemObject).find("input, textarea, select").each(function(iter){
	     old_values[iter] = $(this).val();
	});
        // Change Numbers
        $(itemObject).html(
			      $(itemObject)
			      .html()
			      .replace(new RegExp("course_chapters_attributes_"+old_chapter_id,"gi"),"course_chapters_attributes_"+new_chapter_id)
			      .replace(new RegExp("course.chapters_attributes.."+old_chapter_id+"\]","gi"),"course\[chapters_attributes\]\["+new_chapter_id+"\]")
			      .replace(new RegExp("content_items_attributes_"+old_item_id,"gi"),"content_items_attributes_"+new_item_id)
			      .replace(new RegExp("content_items_attributes.."+old_item_id+"\]","gi"),"content_items_attributes\]\["+new_item_id+"\]")
                              .replace(new RegExp("content_item_"+old_chapter_id+"_"+old_item_id+"_","gi"),"content_item_"+new_chapter_id+"_"+new_item_id+"_")
			      ).attr("id","content_item_"+new_chapter_id+"_"+new_item_id);
	// Plug old values back in
	$(itemObject).find("input, textarea, select").each(function(iter){
	    $(this).val(old_values[iter]);
	});
        // Change ID
        $("#course_chapters_attributes_"+old_chapter_id+"_content_items_attributes_"+old_item_id+"_id").attr("name","course[chapters_attributes]["+new_chapter_id+"][content_items_attributes]["+new_item_id+"][id]");
	$("#course_chapters_attributes_"+old_chapter_id+"_content_items_attributes_"+old_item_id+"_id").attr("id","course_chapters_attributes_"+new_chapter_id+"_content_items_attributes_"+new_item_id+"_id");
        SocratED.CourseBuilder.renumberItemPostAdd(itemObject, new_chapter_id, new_item_id);
  },

  // Finish Renumbering a content item after its added to the page
  renumberItemPostAdd : function(itemObject, chapter_id, new_id){
        // Change Position Number
        $("#course_chapters_attributes_"+chapter_id+"_content_items_attributes_"+new_id+"_position").val(new_id);
        // Change Visible Number
        $(itemObject).find(".content_item_left").text(parseInt(new_id)+1);
        // Change ID
        $(itemObject).attr("id","content_item_"+chapter_id+"_"+new_id);
  },


  // Find parent chapter id for a given html element
  findChapterId : function(htmlElement){
        return parseInt($(htmlElement).parents(".chapter").attr("id").split("_")[1]);
  },
  // Find parent chapter id and content item id for a given html element
  findItemIds : function(htmlElement){
        results = $(htmlElement).parents(".content_item").attr("id").split("_");
        to_return = new Array();
        to_return['chapter'] = parseInt(results[2]);
        to_return['item'] = parseInt(results[3]);
        return to_return;
  },

  selectType : function(selectElement){
        $(selectElement).parents('.content_item').find('.ci_attr').hide().find('input,textarea').attr('disabled','disabled');
        $(selectElement).parents('.content_item').find('.'+$(selectElement).val()).show().find('input,textarea').attr('disabled','');
  },

  handleScroll : function(top){
    // what the y position of the scroll is
    var y = $(window).scrollTop();
    $("#scroll_position").val(y); // Save scroll for form submit
    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $('#publish_box').addClass('fixed');
    } else {
      // otherwise remove it
      $('#publish_box').removeClass('fixed');
    }
  },

  /*
   *  Show Video Upload Window
   */
  showUploadVideo : function(uploadLink,user_id,course_id){

    // Determine chapter and item id    
    chapter_id = parseInt($(uploadLink).parents('.content_item:first').attr("id").split("_")[2]);
    item_id = parseInt($(uploadLink).parents('.content_item:first').attr("id").split("_")[3]);

    // Set the keys 
    $("#viddler_frame").attr("src","http://up.viddler.com/uploadform/socrated/user_id::"+user_id+":::chapter_id::"+chapter_id+":::item_id::"+item_id+":::course_id::"+course_id);

  },

  /* 
   * Callback once a video is uploaded
   */
  postUploadVideo : function(video_id,chapter_id,item_id){
    // Add the video to the list in every upload video drop down 
    $(".viddler_video_select").append($("<option></option>").attr("value",video_id).text('Uploaded Video'));
    // Select the item on the current chapter / content item
    $("#content_item_"+chapter_id+"_"+item_id+" .viddler_video_select option[value='"+video_id+"']").attr('selected', 'selected');

  }

}

