function removeCo(coID)
	{
	if(coArray.length > 1)
		{
		$.ajax({
		   type: "POST",
		   async: false,
		   url: "/_/results/compare.php",
		   data: "mode=remove&coID="+coID,
		   success: function(data, exit_msg, object)
		   		{
				if (exit_msg=='success')
					{
					coArray = data.toString().split(',');
					$(".compCloseBtn a img").attr('src','/img/buttons/cancel.png'); // change buttons back
					}
		   		}
			});
		
		return true;
		}
	else
		{
		coArray = Array();
		eraseAll();
		parent.location.reload(); // refresh so that menu shows nothing is tagged
		return true;
		}
	
	return false;
	}


function eraseAll()
	{
	$.ajax({
	   type: "POST",
	   async: false,
	   url: "/_/results/compare.php",
	   data: "mode=erase"
	   });
	}


function tagListing(coID, hID, coTitle)
	{
	var cellContent = '<span>' + urldecode(coTitle) + '</span> <a class="remLink" href="javascript:;"><img border="0" src="/img/buttons/slide_menu_delBtn_r1.png" /></a>';
	$('#favTbl').append('<li id="ftr_'+coID+'" rel="'+coID+'" rev="'+hID+'">'+cellContent+'</li>'); // identify row with id and/or rel value (company id)
	}


function tagChkBox(chkbox)
	{
	if (chkbox.is(':checked')) // was ticked
		{
		var ct = $('#favTbl').children().length; // returns a count of li tags.
		var id = chkbox.val();
		
		var haveCoID = false;
		$('#favTbl').children().each(function () {
			if ( $(this).attr('rel')==id )
				haveCoID = true;
			});
		
		if (!haveCoID)
			{
			if (ct==0)
				$('#favBox').fadeIn(200);
			
			//var coTitle = chkbox.next().attr('rel');
			var coTitle = urlencode(chkbox.next().attr('rel'));
			
			tagListing(id, heading_id, coTitle);
			coArray.push(id+'|'+coTitle+'|'+heading_id);
			
			// update session and log the click in one go
			$.ajax({
			   type: "POST",
			   async: false,
			   url: "/_/results/compare.php",
			   data: "mode=save&coID="+id+"&coArray="+urlencode(coArray)
			   });
			   
			}
		}
	else // was unticked
		{
		var ct = $('#favTbl').children().length; // returns a count of li tags.
		var id = chkbox.val();
		
		$('#favTbl').children().each(function () {
			if ( $(this).attr('rel')==id )
				{
				$(this).remove();

				if (ct==1)
					$('#favBox').fadeOut(500);
				
				removeCo(id);
				}
			});
		}
	}



$(function()
	{
	var $uiConfirm = $('<div title="Report this listing?"><input type="hidden" id="ui-cid" /><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 30px 0;"></span>Have you found something wrong with the business info for:<br/><span id="dialog-biz-title" style="color:#319FC3;"></span> ?<br/><br/>Click YES and we\'ll investigate pronto!</p></div>')
		.dialog({
			open: function() {
				cid = $("#ui-cid").val();
				$('.results_tab').find('.incorrect_Lnk').each(function () {
					if ($(this).attr('rel')==cid)
						{
						currentTag = $(this);
						bizTitle = $(this).parent().find('.tagThis').attr('rel');
						}
					});
				$('#dialog-biz-title').text(bizTitle);
				$('.ui-dialog .ui-dialog-buttonpane button').css({ 'float':'none', 'margin-left':'112px' });
				},
			autoOpen: false,
			resizable: false,
			height: 180,
			modal: true,
			buttons: {
				/*
				CANCEL: function(obj) {
					$("#ui-cid").val('');
					$(this).dialog('close');
				  }
				*/
				YES: function() {
					$.ajax({
					   type: "POST",
					   async: false,
					   url: "/inc/incorrect_notify.php",
					   data: "mode=notify&cid="+cid,
					   success: function(retval)
							{
							if (retval=='OK')
								{
								var parentTag = currentTag.parent();
								currentTag.remove();
								parentTag.append('<i>Reported</i>');
								}
							}
						});
					$(this).dialog('close');
				  }
			  },
			close: function() { 
				 $("#ui-cid").val('');
			  }
		});


	$('.results_tab').find('.phoneNo').each(function () {
		//$(this).html('<a href="javascript:;">Show Phone</a>');
		var label = $(this).attr('rev').split('|');
		$(this).html('<a href="javascript:;">'+ label[0] +'</a>');
		if (label[1]=='buzz')
			$(this).attr('rev','buzz');
		else
			$(this).attr('rev','');
		});
	
	
	$('.compareTbl').find('.phoneNoComp').each(function () {
		var label = $(this).attr('rev').split('|');
		$(this).html('<a href="javascript:;">'+ label[0] +'</a>');
		/* if (label[1]=='buzz')
			$(this).attr('rev','buzz');
		else */
			$(this).attr('rev','');
		});
	
	
	$('#headingInfoBox').fadeOut("slow").slideUp("slow");
	$("#headingInfoLink").show("slow");
	
	var seshVars = '';
	
	$.ajax({
	   type: "POST",
	   async: false, // force this to execute before ready event
	   url: "/_/results/compare.php",
	   data: "mode=read",
	   success: function(data, exit_msg, object)
	   		{
			if (exit_msg=='success')
				seshVars = data;
	   		}
		});
	
	if (seshVars)
		{
		coArray = seshVars.toString().split(',');
		
		if ($('#favBox').length)
			{
			if(coArray.length)
				{
				$.each(coArray,function()
					{
					var element = this.split('|');
					tagListing(element[0], element[2], element[1]);				
					
					// need to tick if on screen
					$('.results_tab').find('#fav'+element[0]).each(function () {
						$(this).attr('checked',true);
						});
					});
				}
			else
				$('#favBox').fadeOut(500);
			}
		}
	else
		{
		coArray = Array();
		if ($('#favBox').length)
			$('#favBox').fadeOut(500);
		}
	
	
	$('.remLink').live('click', function() // was removed, needs to untick if on screen
		{
		var id = $(this).parent().attr('rel'); // company ID
		
		$('.results_tab').find('#fav'+id).each(function () {
			$(this).attr('checked',false);
			});
		$(this).parent().remove();
		
		var ct = $('#favTbl').children().length; // returns a count of li tags.
		if (ct==0)
			$('#favBox').fadeOut(500);
		
		removeCo(id);
		});
	
	
	$('.tagThis').live('click', function()
		{
		if ($(this).prev().is(':checked')) // is already ticked
			$(this).prev().attr('checked', false);
		else
			$(this).prev().attr('checked', true);

		tagChkBox($(this).prev());
		});


	$('.fave').live('click', function()
		{
		tagChkBox($(this));
		});


	$('.incorrect_Lnk').live('click', function()
		{
		$("#ui-cid").val( $(this).attr('rel') );
		$uiConfirm.dialog('open');
		});


	$('.tagtimeLnk').live('click', function()
		{
		$.ajax({
			type: "POST",
			url: "/_/results/compare.php",
			data: "tool=chooseTagList&ts="+$(this).attr('rel'),
			success: function(exit_msg)
				{
				if (exit_msg=='OK')
					parent.location.reload(); // new date/time selected... refresh page
				}
			});
		});	
	
	
	$(".compCloseBtn a").click(function()
		{
		var boxID = '#' + $(this).parent().parent().parent().attr('id');
		var idParts = boxID.split('-');
		
		$(".compCloseBtn a img").attr('src','/img/icons/ajax-loader.gif'); // change buttons to wait icons
		
		if (removeCo(idParts[1]))
			$(boxID).remove();
		});

	
	$("#compRemoveAll").click(function()
		{
		eraseAll();
		parent.location.reload();
		});
	

	$("#mapViewMulti").click(function()
		{
		$.ajax({
			type: "POST",
			async: false,
			url: "/_/results/compare.php",
			data: "tool=getCIDs",
			success: function(cidlist)
				{ if (cidlist)
					$('#cidList').val(cidlist); }
			});
		
		if ($('#cidList').val())
			{
			document.forms.mapSearch.submit();
			$('#cidList').val('');
			}
		});

	
	$(".mapViewSingle").click(function()
		{
		$('#cidList').val( $(this).attr('rel') );
		document.forms.mapSearch.submit();
		$('#cidList').val('');
		});
	
	
	$('#quoteOne')
		.jqDrag('.jqDrag')
		.jqm({ trigger:'.quoteOne',
			   modal:true,
			   onShow: function(hash)
			      {
				  hash.w.show();
				  $.ajax({
					type: "POST",
					url: "/_/results/compare.php",
					data: "tool=quoteSingle&coID=" + $(hash.t).attr('rel'),
					success: function(php_output) {
						$('#qOneHTML').html(php_output); }
					});
				  },
			   onHide: function()
				  {
				  parent.location.reload();
				  }
			 });


	$('#quoteAll')
		.jqDrag('.jqDrag')
		.jqm({ trigger:'.quoteAll',
			   modal:true,
			   onShow: function(hash)
			      {
				  hash.w.show();
				  $.ajax({
					type: "POST",
					url: "/_/results/compare.php",
					data: "tool=quoteList",
					success: function(php_output) {
						$('#qAllHTML').html(php_output); }
					});
				  },
			   onHide: function()
				  {
				  parent.location.reload();
				  }
			 });
	
	
	$('.quoteCB').live('click', function() {
		var count = 0;
		$('#qAllChkList').children().children().each(function () {
			if ($(this).val() && $(this).is(':checked'))
				count++;
			});
		
		if (count>5)
			{
			$(this).attr('checked',false);
			alert('Please un-tick a listing before ticking more.');
			}
		});	
	
	
	$('#historyBox')
		.jqDrag('.jqDrag')
		.jqm({ trigger:'.tagHistoryLnk', 
			   modal:true,
			   onShow: function(hash)
			      {
				  hash.w.show();
				  $.ajax({
					type: "POST",
					url: "/_/results/compare.php",
					data: "tool=showHistory",
					success: function(php_output) {
						$('#historyHTML').html(php_output); }
					});
				  }
			 });

	
	$('#saveFavesPop')
		.jqDrag('.jqDrag')
		.jqm({ trigger:'#favSaveBtn', 
			   modal:true,
			   onShow: function(hash)
			      {
				  hash.w.show();
				  $.ajax({
					type: "POST",
					url: "/_/results/compare.php",
					data: "tool=loadFaves",
					success: function(php_output) {
						$('#favsHTML').html(php_output); }
					});
				  }
			 });
	
	
	$('#favSaveFormBtn').live('click', function() {
		var coIDarr = Array();
		$('#favChkList').children().children().each(function () {
				if ($(this).val() && $(this).is(':checked'))
					coIDarr.push( $(this).val() );
			});
		$.ajax({
			type: "POST",
			async: false,
			url: "/_/results/compare.php",
			data: "tool=saveFaves&coIDarr="+coIDarr,
			success: function(exit_msg)
				{
				if (exit_msg=='OK')
					{
					$(".errors").css("color", "green");
					$(".errors").html("List Saved.");
					$(".errors").fadeIn("fast");
					parent.location.reload(); // refresh page since they may have untagged listings
					}
				else
					{
					$(".errors").css("color", "red");
					$(".errors").html(exit_msg);
					$(".errors").fadeIn("fast");
					}
				}
			});
		});
	
	
	
	$(".dropLinkPlus").click(function()
		{
		var idNum = $(this).attr('rel'); 
		$(this).hide();
		$('#multiDrop'+idNum).slideDown("fast");
		});
	
	$(".dropLinkMinus").click(function()
		{
		var idNum = $(this).attr('rel'); 
		$('#multiDrop'+idNum).slideUp("fast");
		var mdOuter = $('#multiDrop'+idNum).parent();
		mdOuter.children(':first').fadeIn();
		});
	
	
	$("#headingInfoCloseBtn").click(function()
		{
		$('#headingInfoBox').fadeOut("slow").slideUp("slow");
		$("#headingInfoLink").show();
		});
	
	$(".offsite_txtTip").click(function()
		{
		$("#headingInfoLink").hide();
		$('#headingInfoBox').slideDown("slow");
		});
	
	
	if($('#headingInfoBox').length) // more effective than typeof function etc
		{
		$("#headingInfoBox .text-wrapper").qtip(
			{
			content: '<div style="font-family:Arial, Helvetica, sans-serif; font-size:11px;">' + $("#headingInfoBox .text-wrapper").html() + '</div>',
			style: { tip:'topMiddle', name:'cream', width:452, border: { width:2 } },
			position: { adjust: { x: -453, y: -5 } }
			});
		}


	$(".phoneNo").click(function()
		{
		var coInfo = $(this).attr('rel').split('|');
		var buzz = $(this).attr('rev');

		$(this).html( '<img style="padding:6px 10px 0px; vertical-align:top;" src="/img/icons/ajax-loader-fb.gif" />' );
		
		$.ajax({
		   type: "POST",
		   async: false,
		   url: "/inc/log_general.php",
		   data: "log_type=" + coInfo[0] + "&src=results&co_id=" + coInfo[1]
		   });
		
		$(this).html( coInfo[2] );
		if (buzz=='buzz')
			$("#ib"+coInfo[1])
				.addClass('triggered')
				.trigger('click');
		});


	$(".phoneNoComp").click(function()
		{
		var coInfo = $(this).attr('rel').split('|');
		$(this).html( '<img style="padding-left:4px;" src="/img/icons/ajax-loader-fb.gif" />' );
		
		$.ajax({
		   type: "POST",
		   async: false,
		   url: "/inc/log_general.php",
		   data: "log_type=" + coInfo[0] + "&src=results&co_id=" + coInfo[1]
		   });
		
		$(this).html( coInfo[2] );
		});
	
	
	$(".pgNoLnk").click(function()
		{
		/*
		var pgElement = $(this).attr('rel').split('|');
		
		$('#pNum').val( pgElement[0] );
		$('#cid').val( pgElement[1] );
		$('#filters').val( pgElement[2] );
		
		$('#radCat').attr('disabled','disabled');
		$('#radName').attr('disabled','disabled');
		
		var pID = $('#pID').val();
		if (pID=="")
			$('#pID').attr('disabled','disabled');
		
		var filters = $('#filters').val();
		if (filters=="")
			$('#filters').attr('disabled','disabled');
		
		var hid = $('#cid').val();
		if (hid=="")
			$('#cid').attr('disabled','disabled');
		
		var noRecs = $('#noRecs').val();
		if (noRecs=="")
			$('#noRecs').attr('disabled','disabled');
		
		document.forms.bloo_form.submit();

		var qString = $(this).attr('rel');
		if (qString)
			parent.location = qString;
		*/

		var pgElement = $(this).attr('rel').split('|');
		if (pgElement[0]=='n')
			{
			$('#pNum').val( pgElement[1] );
			$('#cid').val( pgElement[2] );
			$('#filters').val( pgElement[3] );
			
			$('#radCat').attr('disabled','disabled');
			$('#radName').attr('disabled','disabled');
			
			var pID = $('#pID').val();
			if (pID=="")
				$('#pID').attr('disabled','disabled');
			
			var filters = $('#filters').val();
			if (filters=="")
				$('#filters').attr('disabled','disabled');
			
			var hid = $('#cid').val();
			if (hid=="")
				$('#cid').attr('disabled','disabled');
			
			var noRecs = $('#noRecs').val();
			if (noRecs=="")
				$('#noRecs').attr('disabled','disabled');
			
			document.forms.bloo_form.submit();
			}
		else if (pgElement[1]) // [0] == h (heading)
			parent.location = pgElement[1];

		});


	$("#adminToggle").click(function()
		{
		if ($(this).val()=='Hide')
			{
			$(".adminCust").fadeOut("fast");
			$(".adminMulti").fadeOut("fast");
			$("#adminReset").fadeOut("fast");
			$(this).val('Show');
			}
		else
			{
			$(this).val('Hide');
			$("#adminReset").fadeIn("fast");
			$(".adminMulti").fadeIn("fast");
			$(".adminCust").fadeIn("fast");
			}
		});

	});
