/*
 * attaches event listeners for the fixes/problems view.
 */
function attachEditListener(id, editString) {
	elementID = '#' + id;
	$(elementID).focus(function(){
		if($(this).val()==editString)
			$(this).val('');
	});
	$(elementID).blur(function(){
		if($(this).val()=='')
			$(this).val(editString);
	});
}

function attachFixesProblemEventListeners()
{
	$(".sort-link").live('click', function(e) {
		e.preventDefault();

		$(this).siblings(".expand-window").css('display', '');
	});

	$(".close").live('click', function(e) {
		e.preventDefault();

		$(this).parents(".expand-window").css('display', 'none');
	});

	$(".ajax_close").live('click', function(e) {
		e.preventDefault();

		$(this).parent("div").siblings(".expand-window").find("input").val('');

		applyFilter();
	});
	
	$("#FixProblemsForm").live('submit', function(e) {
		e.preventDefault();

		applyFilter($(this));
	});

	$(".status-list").live('mouseover', function(e) {
		$(this).children(".statusdropdown").css('display', '');
	});

	$(".status-list").live('mouseout', function(e) {
		$(this).children(".statusdropdown").css('display', 'none');
	});
	
	$(".employee-list").live('mouseover', function(e) {
		$(this).children(".employeedropdown").css('display', '');
	});

	$(".employee-list").live('mouseout', function(e) {
		$(this).children(".employeedropdown").css('display', 'none');
	});

	$(".status-head-list").live('click', function(e) {
		e.preventDefault();
		
		applyFilter($(this));
	});
	
	$(".comment").each(function() {
		$(this).click(function() {
			var url = $(this).attr("rel");

			$('#dialog').load(url).dialog({autoOpen:false, modal:true, width:500, resizable:false});
			$('#dialog').dialog('open');
			
		});
	});

	$(".ideas").click(function() {
		var url = $(this).attr("rel");

		$('#edit-ideas-dialog').load(url).dialog({
				autoOpen:false,
				modal:true, 
				width:500, 
				resizable:false
		});
		
		$("#edit-ideas-dialog").dialog("open");
	});
	
	$(".changestatus, .assignemployee").live('click', function(e) {
		e.preventDefault();

		var action = $(this).attr("href");
		var elem = $(this).parents("td");

		$.ajax({
			type: "GET",
			url: action,

			success: function(msg){
				elem.html(msg);
			}
		});
	});
}

/*
 * filterDropDown
 * 
 * The handler for click event of drop downs on fixes/problems page.
 */
function filterDropDown(id, type) {
	var divid = type+"_"+id;

	$("#status").val(id);
	
	applyFilter();
}

/*
 * orderByReplies
 * 
 * Order the resultset by replies.
 */
function orderByReplies(order) {
	$("#input_Replies").val(order);

	applyFilter();
}

/*
 * orderByVotes
 * 
 * Order the resultset by votes.
 */
function orderByVotes(order) {
	$("#input_Votes").val(order);

	applyFilter();
}


/*
 * The function to filter the results on employee page.
 */
function applyFilter(elem) {
	var actionUrl = $("#FixProblemsForm").attr("action");

	if ($("#title").val().length != 0) {
	 	actionUrl += "/" + "title:"+$("#title").val();
	} 

	if ($("#employee").val().length != 0) {
	 	actionUrl += "/" + "employee:"+$("#employee").val();
	} 	

	var status = $("#status").val();

	if (status != null && status.length != 0) {
	 	actionUrl += "/" + "status:"+status;
	}

	var repliesOrder = $("#input_Replies").val();

	if (repliesOrder != null && repliesOrder.length != 0) {
	 	actionUrl += "/" + "replies:"+repliesOrder;
	}

	var votesOrder = $("#input_Votes").val();

	if (votesOrder != null && votesOrder.length != 0) {
	 	actionUrl += "/" + "votes:"+votesOrder;
	}

	$.ajax({
		type: "GET",
		url: actionUrl,

		success: function(msg){
			$("#productFixListDiv").html(msg);
		}
	});
}

/*
 * Attaches the events to the fixes/searchproduct page.
 */
function attachFixesSearchproductEventListeners()
{
	// Event listener when me too want it fixed is clicked.
	$(".me_too_want_fixed").click(function(e) {
		e.preventDefault();

		var elem = $(this);
		$.ajax({
			type: "GET",
			url: elem.attr("href"),
			success: function(msg){
				var elem_id = elem.attr("rel");
	
				elem.parent("span").html("<p><strong>including you!</strong></p>");
	
				// Update the Fix count.
				var fixCountElem = $("#fixcount_" + elem_id);
				var curCount = parseInt(fixCountElem.text());
	
				fixCountElem.text(curCount + 1);
			}
		});
	});
	
	$(".add-comment-link").click(function(e) {
		e.preventDefault();
		
		$(this).next(".add-comment").show();
	});
	
	$(".list-comments-link").click(function(e) {
		e.preventDefault();
		
		var comments_expand = $(this).next(".comments-expand");
		
		comments_expand.toggle();

		var value = comments_expand.children(".comments-ul");

		comments_expand.children(".comments-ul").load($(this).attr("href"));
	});
}

/*
 * attachAnonymousCommentListener
 * 
 * attach Comment posting listener for the anonymous user.
 */
function attachAnonymousCommentListener()
{
	$(".comment").click(function(e) {
		e.preventDefault();

		var comment_area = $(this).prev("textarea");
		var comment = comment_area.val();
		var fix = $(this).siblings("input").val();
		var commentformid = "commentform" + fix; 
		$("#"+commentformid).validate().form();
		if($("#"+commentformid).validate().form() == false) {
			return false;
		}
		var url = $(this).attr("href") + "/comment:" + escape(comment)+'/fix:'+fix;

		comment_area.attr("disabled", true);

		$('#dialog').load(url, {}, function() {
			$('.close').click(function(e) {
				e.preventDefault();

				$('#dialog').dialog('destroy');
				comment_area.attr("disabled", false);
			});

			$('#cancel').click(function(e) {
				e.preventDefault();

				$('#dialog').dialog('destroy');
				comment_area.attr("disabled", false);				
			});			
		}).dialog({autoOpen:false, modal:true, width:500, resizable:false});

		$("#dialog").dialog('open');
	});	
}

/*
 * attachLoggedInCommentListener
 * 
 * attach Comment posting listener for a logged in user.
 */
function attachLoggedInCommentListener() {
	$(".comment").click(function(e) {
		e.preventDefault();
	
		var comment_area = $(this).prev("textarea");
		var comment = comment_area.val();
		var fix = $(this).siblings("input").val();
		var commentformid = "commentform" + fix;
		$("#"+commentformid).validate().form();
		if($("#"+commentformid).validate().form() == false) {
			
			return false;
		}
		var container = $(this).parent("div").siblings("div.comments").children("ul.comments");
		var outer_container = $(this).closest('div.comment-container-outer');
	
		comment_area.attr("disabled", true);
		var url = $(this).attr("href");
	
		$.ajax({
			type: "POST",
			url: $(this).attr("href"),
			data: "data[Comment][description]="+escape(comment)+"&data[Comment][fix_id]="+fix,
			success: function(msg){
				var num_comments = parseInt(outer_container.find(".fix-counts").html());
				
					outer_container.find(".fix-counts").html(num_comments + 1);
					container.prepend(msg);
					comment_area.attr("disabled", false);
					comment_area.val("");
				
			}
		});
	});
}

function attachAjaxCommentsListListeners()
{
    $(".paging").find('a').click(function(event) {	
		event.preventDefault();

		var ul_container = $(this).parents("div.comments");

		// The AJAX call.
		$.ajax({
				type: "POST",
				url: $(this).attr('href'),

				success: function(msg){
					ul_container.html(msg);
				}
			});
	});
}

var check_timeout = '';
var m = -1;	// For general search.
var n = -1;	// For product manufacturers.
var p = -1; // For product names.

//Auto fill functionality starts
function lookup(elem,val,e,searchdiv,url, elemshowstyle, elemhidestyle, searchshowstyle, searchhidestyle, attachReturnListener, ajax_type){
	clearTimeout(check_timeout);

	if (searchdiv == null || typeof searchdiv == "undefined") {
		searchdiv = 'searchresults';
	}
	if (elemshowstyle == null || typeof elemshowstyle == "undefined") {
		elemshowstyle = 'query fancylabel results';
	}
	if (elemhidestyle == null || typeof elemhidestyle == "undefined") {
		elemhidestyle = 'query fancylabel';
	}
	if (searchshowstyle == null || typeof searchshowstyle == "undefined") {
		searchshowstyle = 'searchresults starthiddenshow';
	}
	if (searchhidestyle == null || typeof searchhidestyle == "undefined") {
		searchhidestyle = 'searchresults starthidden';
	}	
	if (attachReturnListener == null || typeof attachReturnListener == "undefined") {
		attachReturnListener = false;
	}
	if (ajax_type == null || typeof ajax_type == "undefined") {
		ajax_type = 'all';
	}	
	
	var keyCode = e.keyCode || window.event.keyCode;

	if (attachReturnListener == true) {
		if(parseInt(keyCode,10) === 13){
			document.getElementById(searchdiv).className = searchhidestyle;
			document.getElementById(elem).className	= elemhidestyle;
			return false;
		}
	}

	var index = -1;
	
	if (ajax_type == 'companies') {
		index = n;
	}
	else if(ajax_type == 'products') {
		index = p;
	}
	else {
		index = m;
	}

	if(parseInt(keyCode,10)===40){
		if (ajax_type == 'companies') {
			index = ++n;
		}
		else if(ajax_type == 'products') {
			index = ++p;
		}
		else {
			index = ++m;
		}

		if(document.getElementById("dropdown_"+ajax_type+"_"+index)){
			$("#dropdown_"+ajax_type+"_"+index).css('background', '#FF8A4A') ;
			$("#dropdown_"+ajax_type+"_"+index).addClass('selected') ;

			if(index>0){
				$("#dropdown_"+ajax_type+"_"+eval(index-1)).css('background','');
				$("#dropdown_"+ajax_type+"_"+eval(index-1)).removeClass('selected') ;
			}

			$("#"+elem).val(($("#dropdown_"+ajax_type+"_"+index).text()));
		}
		else{
			if (ajax_type == 'companies') {
				n--;
			}
			else if(ajax_type == 'products') {
				p--;
			}
			else {
				m--;
			}
		}
		return false;
	}
	if(parseInt(keyCode,10)===38){
		if(index>0){
			$("#dropdown_"+ajax_type+"_"+eval(index-1)).css('background', '#FF8A4A');
			$("#dropdown_"+ajax_type+"_"+eval(index-1)).addClass('selected');
			$("#dropdown_"+ajax_type+"_"+index).css('background', ''); 
			$("#dropdown_"+ajax_type+"_"+index).removeClass('selected'); 
			
			$("#"+elem).val(($("#dropdown_"+ajax_type+"_"+eval(index-1)).text()));

			if (ajax_type == 'companies') {
				n--;
			}
			else if(ajax_type == 'products') {
				p--;
			}
			else {
				m--;
			}
		}
		return false;
	}
	
	if (ajax_type == 'companies') {
		n = -1;
	}
	else if(ajax_type == 'products') {
		p = -1;
	}
	else {
		m = -1;
	}


	if(val && val.length > 1)	{
		 if (typeof url == "undefined") {
			 url = "/lft/searches/index";
		 }
		url = url + "/q:"+val;

		check_timeout = setTimeout(function() {  
		document.getElementById(elem).className	=	'query fancylabel loading';
		$.ajax({
			type: "GET",
			url: url,

			success: function(msg){
			   if(msg.length > 0)	{
					var value = $("#"+elem).val();

					if(value){ 
						document.getElementById(searchdiv).className = searchshowstyle;
						$('#'+searchdiv).html(msg);
						document.getElementById(elem).className	=	elemshowstyle;
					}
			   }
			   else	{
					document.getElementById(searchdiv).className = searchhidestyle;
					$('#'+searchdiv).html('');
					document.getElementById(elem).className	=	elemhidestyle;
			   }			    
		      }
			});
	  	}, 1000);
	  }
	else{		 
		document.getElementById(searchdiv).className = searchhidestyle;
		$('#'+searchdiv).html('');
		document.getElementById(elem).className	=	elemhidestyle;
	  }
}

// To hide autofill div 
function hideListDiv1(elem, val, searchdiv, elemshowstyle, elemhidestyle, searchshowstyle, searchdivstyle, attachReturnListener){		
	$("#"+elem).css('color','#888');
	
	if (typeof searchdiv == "undefined") {
		searchdiv = 'searchresults';
	}
	if (typeof elemshowstyle == "undefined") {
		elemshowstyle = 'query fancylabel results';
	}
	if (typeof elemhidestyle == "undefined") {
		elemhidestyle = 'query fancylabel';
	}
	if (typeof searchshowstyle == "undefined") {
		searchshowstyle = 'searchresults starthiddenshow';
	}
	if (typeof searchhidestyle == "undefined") {
		searchhidestyle = 'searchresults starthidden';
	}
	if (typeof attachReturnListener == "undefined") {
		attachReturnListener = false;
	}	
	
	if(val){
		var anchordiv = "#" + searchdiv + ' #cntofanchor';

		if($(anchordiv)) {
			if($(anchordiv).val()){
				document.onclick = function onclick(event){
					document.getElementById(searchdiv).className = searchhidestyle; 
					document.getElementById(elem).className	=	elemhidestyle;
				};
			}
		}
	}
}

// To show autofill div 
function showDiv1(elem, val, searchdiv, elemshowstyle, elemhidestyle, searchshowstyle, searchdivstyle, attachReturnListener){	
	$('#'+elem).css('color',"#000000");

	if (typeof searchdiv == "undefined") {
		searchdiv = 'searchresults';
	}
	if (typeof elemshowstyle == "undefined") {
		elemshowstyle = 'query fancylabel results';
	}
	if (typeof elemhidestyle == "undefined") {
		elemhidestyle = 'query fancylabel';
	}
	if (typeof searchshowstyle == "undefined") {
		searchshowstyle = 'searchresults starthiddenshow';
	}
	if (typeof searchhidestyle == "undefined") {
		searchhidestyle = 'searchresults starthidden';
	}
	if (typeof attachReturnListener == "undefined") {
		attachReturnListener = false;
	}	
	
	if(val){
		var anchordiv = "#" + searchdiv + ' #cntofanchor';

		if($(anchordiv)){
			if($(anchordiv).val()){
				document.onclick = '';
				document.getElementById(searchdiv).className = searchshowstyle;
				document.getElementById(elem).className	=	elemshowstyle;
			}
		}
	}
}

/*
 * attach Events for the search form.
 */
function attachSearchFormEvents()
{
	$("#SearchIndexForm").submit(function(){
		var url = $(".selected").attr("href");

		if (url != undefined) {
			location.href = url;
			return false;
		}
	});	
}

/*
 * attachEmployeeIndexListeners
 * 
 * attach Listeners to the employee Index page
 */
function attachEmployeeIndexListeners() {
	$('#add_employee_lbl').click(function(e) {
		// stop normal link click
	   	e.preventDefault();
	
	   	$("#add_employee_table_id").toggle();
	
	   	if ($("#add_employee_table_id").is(":visible")) {
			$(this).html("- Add more employees");
		}
	   	else {
	   		$(this).html("+ Add more employees");
		}
	});

	$('#add-employee-link').click(function(e) {
		// stop normal link click
		e.preventDefault();
	
		jQuery.validator.setDefaults({errorClass:'error-msg', errorElement:'span'});

		if ($("#EmployeeIndexForm").valid()) {
			$(this).FormModifier({actionElem:'.addIcon > a',
				cloneElem:'.empClone', cloneRow:true, isParent:true,
				labelPrefix:null, labelDiv:null});

			$(this).data('FormModifier').appendRow();
		}
	});
	
	$('.row-remove-link').live('click', function(e) {
		// stop normal link click
		e.preventDefault();

		$(this).FormModifier({actionElem:'.addIcon > a',
			cloneElem:'.empClone', cloneRow:true, isParent:true,
			labelPrefix:null, labelDiv:null});

		$(this).data('FormModifier').deleteRow();
	});

	$(".edit-employee").click(function(e) {
		e.preventDefault();
		$.ajax({
			url:$(this).attr("href"),
	
			success:function(msg) {
				$("#priceListDiv").css('display', '');
				$("#priceListDiv").html(msg);
			}
		});
	});
}

/*
 * attachAddProductListeners
 * 
 * attach Listeners to the employee Index page
 */
function attachAddProductListeners() {
	$('#add_product_lbl').click(function(e) {
		// stop normal link click
	   	e.preventDefault();
	
	   	$("#ProductAddproductForm").toggle();
	
	});
	
	$('#add-problem-link').click(function(e) {
		e.preventDefault();

		jQuery.validator.addMethod('checkTitle', function(value) {
			        if(value == "Eg: Won't switch off ...") {
			            return false;
			        }
			        return true;
			    }, "Title is a required field");

		jQuery.validator.addMethod('checkDesc', function(value) {
	        if(value == "Describe the problem in full ...") {
	            return false;
	        }
	        return true;
	    }, "Description is a required field");

		jQuery.validator.setDefaults({errorClass:'error-msg', errorElement:'span'});

		if ($("#ProductAddproductForm").valid()) {
			// stop normal link click
			$(this).FormModifier({actionElem:'.addIcon > a',
				cloneElem:'.prodClone', cloneRow:true, isParent:true,
				labelPrefix:null, labelDiv:null});

			$(this).data('FormModifier').appendRow();
		}
	});
	
	$('.row-remove-link').live('click', function(e) {
		// stop normal link click
		e.preventDefault();

		$(this).FormModifier({actionElem:'.addIcon > a',
			cloneElem:'.prodClone', cloneRow:true, isParent:true,
			labelPrefix:null, labelDiv:null});

		$(this).data('FormModifier').deleteRow();
	});
}

/*
 * attachReportAProblemListeners
 * 
 * attach Listeners to the report a problem page
 */
function attachReportAProblemListeners() {
	$('#add-problem-link').click(function(e) {
		e.preventDefault();
	
		jQuery.validator.setDefaults({errorClass:'error-msg', errorElement:'span'});
		jQuery.validator.addMethod('checkTitle', {
			    check: function(value) {
			        if(value == "Eg: Won't switch off ...") {
			            return false;
			        }
			        return true;
			    },
			    msg : "Please enter a valid title."
			 });

		if ($("#ProblemAddForm").valid()) {
			// stop normal link click
			$(this).FormModifier({actionElem:'.addIcon > a',
				cloneElem:'.prodClone', cloneRow:true, isParent:true,
				labelPrefix:null, labelDiv:null});

			$(this).data('FormModifier').appendRow();
		}
		else {
			$("#ProductAddproductForm").validate();
		}
	});
}

/* sendValidationEmail to resend the token for activating a/c */
function sendValidationEmail() {
	$.ajax({
		type: "GET",
		url: $("#URL").val() + 'tokens/resend',
		success: function(msg){
		}
	});
}

function attachEmployeeEditPopupListeners() {
	$(".close-mark").click(function(e) {
		e.preventDefault();
	
		$(this).parents(".sortoptions").css('display', 'none');
	});
	$(".remove").click(function(e) {
		e.preventDefault();
	
		var url = $(this).attr("href");
	
		$.ajax({
			type: "GET",
			url: url,
	
			success: function(msg){
				window.location.reload();
			}
		});
	});
	$(".make-mod").click(function(e) {
		e.preventDefault();
		
		$.ajax({
			url:$(this).attr("href"),
	
			success:function(msg) {
				$("#mod-div").css('display', '');
				$("#mod-div").html(msg);
			}
		});
	});
}