/* Page is ready, get working...
*/

$(document).ready(function() {
    $("#editTreeView").treeview({
       collapsed: false,
       control: "#treeViewControls"
    });
    Listing_EditOnly("#listingCat"); // Grab changes to Cats
    statusUpdate("#listingStatus","#lStatus"); // Grab changes on status, and make ajax submit
    makeFaq();
	confirmDeletion();
	
	if($("#editTreeView")) {
		object_controls();
		$.hotkeys.add('Ctrl+s', function(){ 
			$('#listings').submit();
			//alert("yaarr!");
		});
	};

});

function confirmDeletion() {
	$('a.delete').click(function(){
    	return confirm('Please confirm deletion...');	
	}); 
}

function object_controls() {
	$(".collapsable").mouseover(function() {
		$(this).children("span").children(".controls").show();
	})
	$(".collapsable").mouseout(function() {
		$(this).children("span").children(".controls").hide();
	})
	$(".expandable").mouseover(function() {
		$(this).children(".controls").show();
	})
	$(".expandable").mouseout(function() {
		$(this).children(".controls").hide();
	})
	$(".folder").mouseover(function() {
		$(this).children(".controls").show();
	})
	$(".folder").mouseout(function() {
		$(this).children(".controls").hide();
	})
}


function allowed_fieldType() {
    var p = $("#allowedValues");
    $.get("/field_type/allowed_types", 
        function(data){ 
            $(p).append(data);
        } 
);
}

function faqEntry() {
    var p = $("#faqEntries");
    $.get("/faq/entry_input", 
        function(data){ 
            $(p).append(data);
        } 
);
}

function lineItem() {
    var p = $("#lineItems");
    $.get("/order/line_item", 
        function(data){ 
            $(p).append(data);
        } 
);
}

function makeModal(obj) {
	var txt = $(obj).attr("alt");
	tb_show("Create new Object.",txt);
}

function makeFaq () {
	$(".faq_answer").hide();
	$(".faq_question a").click(function(){
		$(".faq_answer:visible").slideUp("fast");
		$(this).next().slideDown("fast");
		return false;
	});
}

function ontologyMove (whereFrom, whereTo) {

    selected = $(whereFrom).children('option:selected');      
    if (selected.length > 0) {
        //console.log("Output: " + $(selected).text()); // debugging
        
        $(selected).appendTo(whereTo);
        //$(selected).remove();        
                       
        $(whereFrom).children('option:selected').attr("selected",""); // Deselect.
        $(whereTo).children('option:selected').attr("selected",""); // Deselect.
    }
 
};

function ontologyCopy (whereFrom, whereTo) {

    selected = $(whereFrom).children('option:selected');      
    if (selected.length > 0) {
        //console.log("Output: " + $(selected).text()); // debugging
        
        $(selected).clone().appendTo(whereTo);
        //$(selected).remove();        
                       
        //$(whereFrom).children('option:selected').attr("selected",""); // Deselect.
        //$(whereTo).children('option:selected').attr("selected",""); // Deselect.
    }
 
};

function ontologyDelete (whereFrom) {

    selected = $(whereFrom).children('option:selected');      
    if (selected.length > 0) {
        //console.log("Output: " + $(selected).text()); // debugging
        
        $(selected).remove();      
                       
        $(whereFrom).children('option:selected').attr("selected",""); // Deselect.
    }
 
};

function selectAll(multiSelectBox) {

    $(multiSelectBox).children().attr({selected: "selected"});

}

function copy_item(obj, field_typeID, listingId){
    var field_name = $(obj).parent().children('input').attr('name');
	var ajaxString = "/listing/create_tree_item/" + listingId;
	
	appendTo = $(obj).parent().parent().parent().parent().children("class: folder").children('input').attr('name');
	
	if (appendTo == null || appendTo == "") { appendTo = "" };
	//console.log (appendTo);
	$.post(ajaxString, { 
		class_or_fields: "fields-" + field_typeID +"", 
		modal_objectTo_appendTo: appendTo
		}, 
			function(data){
				branches = $(obj).parent().parent().after(data);
					$("#editTreeView").treeview({
				        add: branches
				     });
			} 
		);
		object_controls();
		
}

function copy_obj(obj, object_typeID, listingId){
    var field_name = $(obj).parent().children('input').attr('name');
	var ajaxString = "/listing/create_tree_item/" + listingId;
	
	object0r = $(obj).parent().parent().parent();
	
	appendTo = $(object0r).children("class: folder").children('input').attr('name');
	
	a = appendTo;
	var tmp = new Array();
	var i = '0';
	
	tmp = a.split('[objects]');
	//console.log ('start with:'+appendTo);
	var z = '';
	//console.log(tmp.length+'-array length')
	for (i in tmp){
		//console.log(tmp[i]);
		if (i < tmp.length -1 ) {
			if (i <= 0) {
				z = tmp[i];
			} else {
				z = z + '[objects]' + tmp[i];
			}
		}
	};
	//console.log ('end with:'+z);
	appendTo = z; 
	
	if (appendTo == null || appendTo == "") { 
		appendTo = "";
		//console.log(appendTo+': case1 - root level.');
	}
	$.post(ajaxString, { 
		class_or_fields: "classes-" + object_typeID +"", 
		modal_objectTo_appendTo: appendTo
		}, 
			function(data){
				branches = $(obj).parent().parent().parent().after(data);
					$("#editTreeView").treeview({
				        add: branches
				     });
			// Add fieldTypes here..:
			var parentObj = $(obj).parent().parent().parent();
			var childObj = $(parentObj).children('ul').children('li').children('span').children('.copyNew');
				$(childObj).each(function(){ // This is pretty Kludgy. Used to get the field_type from each child.	
					var a = $(this).attr('onClick');
					var temp = new Array();
					a = a.toString(); //Fix for ie7.
					temp = a.split(",");
					field_typeID = temp[1];// get text after first ',' till next ','
					
					var toWhat = $(parentObj).next();
					
					appendTo = $(toWhat).children().children('input').attr('name');
					$.post(ajaxString, { 
						class_or_fields: "fields-" + field_typeID +"",
						modal_objectTo_appendTo: appendTo 
						}, 
							function(data){
								branches = $(toWhat).children('ul').append(data);
									$("#editTreeView").treeview({
								        add: branches
								     });
									 object_controls();
							} 
						);
					
				});	
			} 
		);
}


function addClass_or_Field() {
    var checked = $(this).find("input:checked");
    var checked_value = checked.attr("value");
    var goingTo = $(this).find("#modal_objectTo_appendTo").attr("value");
	selected = $("#availableOntology").children('option:selected');      
    if (selected.length > 0) {
		$("#commit").hide();
		//checked_parts = checked_value.split('-');
		//goingTo = goingTo + "["+checked_parts[0]+"]";
		//goingTo = goingTo + "["+checked_parts[1]+"]";
		//console.log(checked_parts)
		//console.log(goingTo)
		
		$('#jointForm').ajaxSubmit({
			success: add_TreeItem
		});
	}
    
}

function add_TreeItem(responseText, statusText){
    var goingTo = $("#modal_objectTo_appendTo").attr("value");
    var objectToAddTo = $("#editTreeView").find("input").filter("[name='" + goingTo + "']");
    
    if (goingTo != null && goingTo != "") {
        toAppendTo = objectToAddTo.parent().parent().children('ul')
        branches = $(responseText).appendTo(toAppendTo);
   } else {
        branches = $('#editTreeView').append(responseText);
    }
    
    $("#editTreeView").treeview({
        add: branches
     });
	 
	 tb_remove();
	 object_controls();

}

function statusUpdate (whichSelect,whichForm) {
    $(whichSelect).change(function() {
        $(whichForm).ajaxSubmit({success: function(responseText, statusText) {
            
            }
        });
    });
}

 
function Listing_EditOnly (whichSelect) {
    // Grab the mouseup(s) of each child (was children().children()
    
    $(whichSelect).change(function() {
       objParentLabel = $(this).find('option:selected').parent().attr("label"); // Get this object's parent's label.
       optgroupAdd = $("optgroup[label='Add']");
       optgroupRemove = $("optgroup[label='Remove']");
       selected = $(this).find('option:selected');
       
           if (objParentLabel == "Add") {

               sort_and_submit(selected,optgroupRemove);
                               
           } else if (objParentLabel == "Remove") {
             
               sort_and_submit(selected,optgroupAdd);
               
            } else if ($(selected).val() == "newCat" && selected.attr('class') == "newCat") {
                 tb_show("Create New Label.","#TB_inline?height=95&amp;width=390&amp;inlineId=makeNewCat&modal=true");
            }
            $(this).children('#nullOpt').attr({selected: "selected"});
    })
};

function sort_and_submit(selected, addTo) {
     if ($(selected).text() < addTo.children().slice(0,1).text()) {
             $(selected).prependTo(addTo);             
     } else if ($(selected).text() < addTo.children().slice(-1).text()) {

              addTo.children().each(function() {
              var current = $(this);
              var next = current.next();

                 if ($(selected).text() > current.text() && $(selected).text() < next.text()) {
                         $(selected).insertAfter(current);
                 }
             });
     } else {
        $(selected).appendTo(addTo);
     }
     $('#catz').ajaxSubmit();
}

function catSubmit_Apply() {
    $('#newCat').ajaxSubmit({success: function(responseText, statusText) {
        if (responseText) {
        catName = $('#category_title').val();
        addTo = $("optgroup[label='Remove']");
        string = "<option value="+responseText+">"+catName+"</option>";
        
             if (catName < addTo.children().slice(0,1).text()) {
                     $(string).prependTo(addTo);             
             } else if (catName < addTo.children().slice(-1).text()) {
        
                      addTo.children().each(function() {
                      var current = $(this);
                      var next = current.next();
        
                         if (catName > current.text() && catName < next.text()) {
                                 $(string).insertAfter(current);
                         }
                     });
             } else {
                $(string).appendTo(addTo);
             }
        
        }
    }});
    tb_remove();

    $('#nullOpt').attr({selected: "selected"});
}
/*
function makeEditable() {
    // Add the inline edit for pre-existing listings.
    $(".editable").click( function() {    // dblclick breaks in Opera9
    var1 = $(this).children(".t").text(); // Field Type
    var2 = $(this).children(".v").text(); // Field Value
    var3 = $(this).children(".invis").text(); // DB ID
    var id = $(".row").length;
    whatToAdd = "<p class='row'>\n<input type='text' size='30' name='fieldType["+id+"]' id='fieldType_id"+id+"' value='"+var1+"'>\n<input type='text' size='60' name='fieldValue["+id+"]' id='fieldValue_id"+id+"' value='"+var2+"'>&nbsp;&nbsp;\n<a href='#' class='copyExisting' onClick='copyExistingField($(this).parent()); return false;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>\n<a href='#' class='removeField' onClick='markForDeletion($(this).parent().parent()); return false;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>\n<input type='hidden' name='fieldID["+id+"]' class='existingItem' value='"+var3+"' /><input type='hidden' name='delete["+id+"]' class='deleteItem' value='0' /></p>";
    addFormField(whatToAdd,$(this).parent(),'0');
    $(this).hide(); // Hide it, was $(this).remove();
    
    } );
    
    $(".editable").mouseover( function() {
        $(this).highlightFade({color: '#FAFFF3', speed: 'fast', end: '#ffff99'});
    } );
    $(".editable").mouseout( function() {
        $(this).highlightFade({color: '#ffff99', speed:'fast', end: '#FAFFF3'});
    } );  
    
}
*/
/*
function returnEditable(destroy,showme,autocomplete) {
    destroy.remove();
    showme.show();
}
*/
/*
function disableButton() {

    if ($(".row").length < 1) {
        $(".confirmButton").hide();
    } else {
        $(".confirmButton").show();
    }
}
*/
/*
function deleteDuds() {
// Delete empty new items
$(".row").each(function(i){
    var1 = $(this).children("input:eq(0)"); // First text box.
    var2 = $(this).children("input:eq(1)"); // Second Text box.
    varString1 = $(var1).attr("value");
    varString2 = $(var2).attr("value"); 
 
    if ($(this).children().is(".existingItem") && !$(this).parent().is(".markedToDelete")) {
    
        firstTxt = $(this).prev().children(".t").text(); // Field Type
        secondTxt = $(this).prev().children(".v").text(); // Field Value
        
        if (firstTxt == varString1 && secondTxt == varString2) {                
            returnEditable($(this).parent().children(".row"), $(this).parent().children(".editable"));
        }

    } else if ($(this).parent().is(".markedToDelete")) {
        // to be deleted. 
    } else {
        // neither, either something broke or this is a new item.
        
        if (varString1 == null && varString2 == null || varString1 == "" && varString2 == "") {
            $(this).parent().remove(); // Both fields empty. Kill it.
        }

    }

});
}
*/
/*
function checkEmpty() {
var err0r=new Boolean()
$(".row").each(function(i){
    var1 = $(this).children("input:eq(0)"); // First text box.
    var2 = $(this).children("input:eq(1)"); // Second Text box.
    varString1 = $(var1).attr("value");
    varString2 = $(var2).attr("value");
// empty field somewhere...

    if (varString1 == null || varString1 == "") {
        var1.addClass("error");
        err0r = "true";
    }
    if (varString2 == null || varString2 == "") {
        var2.addClass("error");
        err0r = "true";
    }
})
return err0r;
};
*/
/*
function updateConfirm() {
// Added some simple error checking 12/02/07
    // Count all Rows, if there are some do some basic checks;
    if($(".row").length > -1) {

    deleteDuds();

        updates = $(".existingItem").parent().parent().not('.markedToDelete').length;
        newItems = $(".row").parent().not('.markedToDelete').length;
        newItems = (newItems - updates);
        deletions = $(".markedToDelete").length;
        $('#amountUpdates').html("");
        $('#amountDeletions').html("");
        $('#amountNew').html("");
        var v1, v2;
        
        if (updates > 0) {
            v1 = updates+" update";
        }
        if (updates > 1) {
            v1 = v1 +"s";
        }
        if (deletions > 0) {
            v2 = deletions+" deletion";
        }
        if (deletions > 1) {
            v2 = v2 +"s";
        }
        
        if (newItems > 0){
            $('#amountNew').append(newItems + " new");
        }
        $('#amountUpdates').append(v1);
        $('#amountDeletions').append(v2);
     
    if (updates > 0 || deletions > 0 || newItems > 0) {
        if (checkEmpty() != "true") {
         // Open ThickBox
         tb_show("confirm your changes.","#TB_inline?height=200&width=400&inlineId=confirmChanges&modal=true");
         } else {
         // things get highlighted red..
         }
    }   
    disableButton();
    }
}
*/ 
/*
function addFormField(whatToAdd, tObject, dCopy) {

// "whatToAdd" is whatever you want to put inside pObject. 
// Create whatever inside the element "pObject". 
// dCopy: 0 = don't copy previous, 1 = do.
   
    var id = $(".row").length 
    var zx = whatToAdd; // store whatToAdd
        
    if (!whatToAdd || whatToAdd == "blank") { // KLUDGE!!
        whatToAdd = "<div><p class='row'>\n<input type='text' size='30' name='fieldType["+id+"]' id='fieldType_id"+id+"'>\n<input type='text' size='60' name='fieldValue["+id+"]' id='fieldValue_id"+id+"'>&nbsp;&nbsp;\n<a href='#' class='copyNew' onClick='copyNewField($(this).parent()); return false;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>\n<a href='#' class='removeField' onClick='deleteItem($(this).parent().parent(), \"#ac"+id+"\"); return false;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>\n</p></div>";
    };
    
    // Get the last row, who's parent is not marked for Deletion, then return the object
    // of the first input field. Then get it's val() which returns a string.
    var lowestItem = $(this).find('.row:last').parent().not('.markedToDelete').find('.row:last').children('input:eq(0)').val();

    
    $(tObject).append(whatToAdd);  // Acctually create the object(s) here.

    if (dCopy != "0") {
        if (lowestItem != null && lowestItem != ""){  // if the element value of the lowest input type is not empty/null
            $(this).find('.row:last').children('input:eq(0)').val(lowestItem) // set it to the previous.
        }
    }
    
    $($("#fieldType_id" + id).parent()).highlightFade();
    
    // jQuery call to load external java and execute it.
    $.getScript("/public/javascript/jquery.suggest.js", function(){ 
        jQuery("#fieldType_id" + id).suggest("/field_type/get_list",{ objectId: "ac"+id, onSelect: function() {}}); 
    }); 

    disableButton();    
}
*/
/*
function copyExistingField(what) {

    var1 = $(what).children("input:eq(0)"); // First text box.
    var2 = $(what).children("input:eq(1)"); // Second Text box.
    varString1 = $(var1).attr("value");
    varString2 = $(var2).attr("value");
    
    addFormField('',$("#divTxt"),'0');
    
    var lowestItem = $(this).find('.row:last').parent().find('.row:last').children('input:eq(0)');
    var lowestItem2 = $(this).find('.row:last').parent().find('.row:last').children('input:eq(1)');
            
    lowestItem.val(varString1);
    lowestItem2.val(varString2);
}
*/
/*
function copyNewField(what) {

    var1 = $(what).children("input:eq(0)"); // First text box.
    var2 = $(what).children("input:eq(1)"); // Second Text box.
    varString1 = $(var1).attr("value");
    varString2 = $(var2).attr("value");
    
    var id = $(".row").length 
        
    whatToAdd = "<div><p class='row'>\n<input type='text' size='30' name='fieldType["+id+"]' id='fieldType_id"+id+"'>\n<input type='text' size='60' name='fieldValue["+id+"]' id='fieldValue_id"+id+"'>&nbsp;&nbsp;\n<a href='#' class='copyNew' onClick='copyNewField($(this).parent()); return false;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>\n<a href='#' class='removeField' onClick='deleteItem($(this).parent().parent(), \"#ac"+id+"\"); return false;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>\n</p></div>";
       
    $(whatToAdd).insertAfter(what.parent());  // Acctually create the object(s) here.
   
    $($("#fieldType_id" + id).parent()).highlightFade();
    
    // jQuery call to load external java and execute it.
    $.getScript("/public/javascript/jquery.suggest.js", function(){ 
        jQuery("#fieldType_id" + id).suggest("/field_type/get_list",{ objectId: "ac"+id, onSelect: function() {}}); 
    }); 

    disableButton(); 
    
    var lowestItem = $($("#fieldType_id" + id).parent()).children('input:eq(0)');
    var lowestItem2 = $($("#fieldType_id" + id).parent()).children('input:eq(1)');
            
    lowestItem.val(varString1);
    lowestItem2.val(varString2);
}
*/

/*
function makeMenu () {
	$("dd:not(:first)").hide();
	$("dt a").click(function(){
		$("dd:visible").slideUp("fast");
		$(this).parent().next().slideDown("fast");
		return false;
	});
}
*/

/*
function markForDeletion(tObject) {
 
// To mark items for Deletion upon form submission.
// Will append the class of "markedToDelete". 

    // Pass this function the parent div of the row.
    if ($(tObject).attr('class') != "markedToDelete") {  // If it is not already marked..
        $(tObject).highlightFade({color: '#FAFFF3', speed:'fast', end: 'red'});
        $(tObject).addClass('markedToDelete'); 
        $(tObject).children().find('.removeField').removeClass('removeField').addClass('saveField'); // Update ahref
        $(tObject).children().find('.deleteItem').val('1');
    } else {
        $(tObject).highlightFade({color: 'green', speed: 'fast', end: '#FAFFF3'});
        $(tObject).removeClass('markedToDelete');
        $(tObject).children().find('.saveField').removeClass('saveField').addClass('removeField');
        $(tObject).children().find('.deleteItem').val('0');            
    }
    disableButton();
}
*/

/*
function deleteItem(tObject, sObject) {
    $(tObject).highlightFade({color: 'red', speed:'fast', complete: function() {
        $(tObject).remove();
        $(sObject).remove();
        disableButton()
        } 
    });
}*/

/*function remove_parentLi(obj) {

    $(obj).parent().parent("li").remove();
}*/

