/**
* File: Petciety,js
* Description: Core functionality for the Petciety.com web site
*
**/
// When the page is ready, connect the events
$(document).ready( function(){
	Petciety.init(); 
	if($.browser.msie && $.browser.version < 7 && (document.body.filters)) 
   	{
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }
		 
});

var Petciety = {};

Petciety.OBJECT_ROW_PREFIX = "object_row_";

Petciety.init = function()
{
	$(".browse-filter-header").bind('click', function(event) {
		Petciety.showBrowseFilter(event.target);
	});
	$('.browse-filter-section input:checkbox').each( function() {
		 var _checked = this.checked;
		 
		 if(_checked) { 
		 	var _parent = $(this).parent().parent();
		 	var _trigger = _parent.prev();
		 	if(_parent.css('display') != 'block')_trigger.click();
		 }
	});
	var _distance = $("#distance_select").val()
	if(_distance != "") { $("#distance").click(); } 
	
	// Fix the height of the oranage vertical line if necessary
	Petciety.fixVerticalLineHeight();
	
	// For the jobs page we need to look for any details to show
	if($("#job_detail_id").length > 0)
	{
		var _id = $("#job_detail_id").val();
		if(_id > 0 && $("#" + Petciety.OBJECT_ROW_PREFIX + _id).length > 0)
		{
			Petciety.showJobDetails(_id);
		}
	}
}

Petciety.fixVerticalLineHeight = function()
{
	// Fix the height of the left col if necessary
	var _main_content = $('.main-content').height();
	var _main_height = $('#page-main').height();
	_main_content = _main_content > 600 ? _main_content : 600;
	if(_main_height && _main_height < _main_content) $('#page-main').height(_main_content);
	
}
/**
* Details panels
*/
Petciety.showObjectDetails = function(objectId, url, pos_top_id, pos_left_id, callback)
{
	if($('#details_panel').length == 0)
	{
		if($('.listing').length > 0) $('.listing').append('<div id="details_panel"></div>');
		else $('.public-listing').append('<div id="details_panel"></div>');
		
	}
	// Hide any other details
	//$('#details_panel').hide();
	$('#details_panel').html('<div class="loading">&nbsp;</div>');
	// Load the content
	url = objectId ? url + '/' + objectId : url;
	$('#details_panel').load(url, {}, function() {Petciety.fixVerticalLineHeight();});
	$('#details_panel').width($('.object_list').width() - 2);
	// If pos, use that for positioning
	//if(pos_top_id) pos_top_id = "#" + pos_top_id;
	//else pos_top_id = "#" + Petciety.OBJECT_ROW_PREFIX + objectId;
	if(pos_left_id) pos_left_id = "#" + pos_left_id;
	else pos_left_id = "#" + Petciety.OBJECT_ROW_PREFIX + objectId;
	
	// Position the details
	//var _offset_top = $(pos_top_id).position();
	//var _offset_left = $(pos_left_id).position();
	// Details are always presented below the row that they are triggered in, so we need to add the height of the row to the top offset
	//$('#details_panel').css("top",_offset_top.top + $(pos_top_id).height());
	//$('#details_panel').css("left",_offset_left.left + "px");
	// Show the details
	$('#details_panel').appendTo(pos_left_id);
	$('#details_panel').show();
	if(callback) {  callback(objectId); }
	
}
Petciety.hideDetails = function()  
{ 
	$('#details_panel').hide(); 
	Petciety.fixVerticalLineHeight();
	
}


/**
* Dialog boxes
*/
Petciety.showDialog = function(url, window_class)
{
	if($('#dialog_holder').length != 1) $('body').append('<div id="dialog_holder"></div>')
	_class = window_class ? window_class : "jqmWindow";
	$('#dialog_holder').empty();
	$('#dialog_holder').html('<div class="'+_class+'" id="dialog"></div>')
	$('#dialog').jqm( { ajax: url } ).jqmShow();
}

Petciety.closeDialog = function(url) { $('#dialog').jqmHide(); }
Petciety.submitDialogForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.dialogSubmitSuccess });
}
Petciety.dialogSubmitSuccess = function(response) { $("#dialog_content").html(response); }


/**
* Job related
*
*/ 
Petciety.deleteJob = function(id) {  Petciety.showDialog('/ws/job_delete/' + id); }

Petciety.openJobContact = function(sitter_id) 
{ 
	Petciety.showDialog('/ws/open_job_contact/' + sitter_id); 
}
Petciety.openJobInquiry = function(job_id) 
{ 
	Petciety.showDialog('/ws/open_job_inquiry/' + job_id); 
}

Petciety.makeJobOffer = function(job_id, sitter_id) 
{ 
	//$('#potential_sitters').hide();
	//$('#sitter_profile').hide();
	//$('#offer_panel').load('/ws/job_offer/' + job_id + "/" + sitter_id);
	//$('#offer_panel').show();
	$("#message-static").hide(); 
	$("#message-reply").load('/ws/job_offer/' + job_id + "/" + sitter_id);
	$("#message-reply").show(); 
	
}
Petciety.contactAboutJob = function(job_id, sitter_id) 
{ 
	$('#potential_sitters').hide();
	$('#sitter_profile').hide();
	$('#offer_panel').load('/ws/job_contact/' + job_id + "/" + sitter_id);
	$('#offer_panel').show();
	
}
Petciety.cancelJobOffer = function() 
{ 
	//$('#offer_panel').hide();
	//$('#potential_sitters').show();
	$("#message-static").show(); 
	$("#message-reply").hide(); 
	
}
Petciety.cancelJobContact = function() 
{ 
	$('#offer_panel').hide();
	$('#potential_sitters').show();
	
}
Petciety.submitJobContact = function()
{
	$("#job_contact_form").ajaxSubmit( { success: Petciety.jobContactSuccess });
}
Petciety.jobContactSuccess = function(response) 
{ 
	$('#potential_sitters').show();
	$('#offer_panel').hide();
	$("#job_offer_content").html(response); 
}

Petciety.submitJobOffer = function()
{
	$("#job_offer_form").ajaxSubmit( { success: Petciety.jobOfferSuccess });
	$("#message-static").show(); 
	$("#message-reply").hide(); 
}
Petciety.jobOfferSuccess = function(response) 
{ 
	//$('#potential_sitters').show();
	//$('#offer_panel').hide();
	//$("#job_offer_content").html(response); 
	
	$('#reply-server-response').html(response);
	$('.action-buttons').hide();
}
Petciety.submitOpenJobContactForm = function(form_id)
{
	$("#" + form_id).ajaxSubmit( { success: Petciety.openJobContactSuccess });
}
Petciety.openJobContactSuccess = function(response) 
{ 
	$('#dialog').jqmHide();
	$("#global_message").html(response).show();
}
Petciety.submitOpenJobInquiryForm = function(form_id)
{
	$("#" + form_id).ajaxSubmit( { success: Petciety.openJobInquirySuccess });
}
Petciety.openJobInquirySuccess = function(response) 
{ 
	$('#dialog').jqmHide();
	$("#global_message").html(response).show();
}
Petciety.doJobUnassignment = function(job_id, sitter_id) 
{ 
	$('#potential_sitters').hide();
	$('#sitter_profile').hide();
	$('#offer_panel').load('/ws/job_unassignment/' + job_id);
	$('#offer_panel').show();
	
}
Petciety.doJobAssignment = function(job_id, sitter_id) 
{ 
	$('#potential_sitters').hide();
	$('#sitter_profile').hide();
	$('#offer_panel').load('/ws/job_assignment/' + job_id + "/" + sitter_id);
	$('#offer_panel').show();
	
}
Petciety.cancelJobAssignment = function(job_id, sitter_id) 
{ 
	$('#offer_panel').hide();
	$('#potential_sitters').show();
	
}
Petciety.submitJobAssignment = function()
{
	$("#job_assignment_form").ajaxSubmit( { success: Petciety.jobAssignmentSuccess });
}
Petciety.jobAssignmentSuccess = function(response) 
{ 
	$('#potential_sitters').show();
	$('#offer_panel').hide();
	$("#job_offer_content").html(response); 
}
Petciety.submitJobUnassignment = function()
{
	$("#job_unassignment_form").ajaxSubmit( { success: Petciety.jobUnassignmentSuccess });
}
Petciety.jobUnassignmentSuccess = function(response) 
{ 
	$('#potential_sitters').show();
	$('#offer_panel').hide();
	$(".assigned-status").html(response); 
}

Petciety.acceptJobOffer = function(message_id) 
{ 
	Petciety.messageReply (message_id, '/ws/job_response/accept/')	
}
Petciety.rejectJobOffer = function(message_id) 
{ 
	Petciety.messageReply (message_id, '/ws/job_response/reject/')
}


Petciety.showJobDetails = function(id) { Petciety.showObjectDetails(id, '/ws/job_details'); }
Petciety.showBrowseJobDetails = function(id) { Petciety.showObjectDetails(id, '/ws/browse_job_details'); }
Petciety.showPublicJobDetails = function(id) { Petciety.showObjectDetails(id, '/public/job_details'); }
Petciety.showRatingJobDetails = function(id, pos_top, pos_left) { Petciety.showObjectDetails(id, '/ws/job_details', pos_top, pos_left); }

Petciety.forwardToMember = function(id) { Petciety.showObjectDetails(id, '/ws/job_pick_sitter'); }

Petciety.assignJob = function(id) { Petciety.showObjectDetails(id, '/ws/job_assign_sitter'); }

Petciety.showSitterDetails = function(id, action_type, job_id) 
{ 
	$('#offer_panel').hide();
	$('#potential_sitters').hide();
	$('#sitter_profile').html("Loading...");
	$('#sitter_profile').load('/ws/sitter_profile/' + action_type + '/' + job_id+ '/' + id);
	$('#sitter_profile').show();
}
Petciety.hideSitterDetails = function() 
{ 
	$('#potential_sitters').show();
	$('#sitter_profile').hide();
}

Petciety.reloadJobsListing= function( is_delete )
{
	sort = $("#sort").val();
	sort_order = $("#sort_order").val();
	page = $("#page_num").val();
	role = $("#role").val();
	age = $("#age").val();
	if(is_delete) 
		$('#job_listing').load('/home/jobs_reload/'+role+"/"+age+"/desc/1");
	else 
		$('#job_listing').load('/home/jobs_reload/'+role+"/"+age+"/"+sort+"/"+page);
}

Petciety.submitJobActionForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.jobActionSubmitSuccess });
}
Petciety.jobActionSubmitSuccess = function(response) 
{ 
	$("#dialog_content").html(response); 
	Petciety.reloadJobsListing( true );
}

/**
* Password reminder
*/
Petciety.forgotPassword = function(id) {  Petciety.showDialog('/ws/forgot_password'); }
Petciety.submitForgotPasswordForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.forgotPasswordFormSuccess });
}
Petciety.forgotPasswordFormSuccess = function(response) 
{ 
	//$('#dialog').jqmHide();
	$("#server_response").html(response).show();
}
/**
* Friend requests
*
*
*/
Petciety.friendRequest = function(id) {  Petciety.showDialog('/ws/friend_request/' + id); }
Petciety.submitFriendRequestForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.friendRequestFormSuccess });
}
Petciety.friendRequestFormSuccess = function(response) 
{ 
	$('#dialog').jqmHide();
	$("#global_message").html(response).show();
}

Petciety.acceptFriendRequest = function(message_id) 
{ 
	Petciety.messageReply (message_id, '/ws/friend_request_accept/')
}
Petciety.rejectFriendRequest = function(message_id) 
{ 
	Petciety.messageReply(message_id, '/ws/friend_request_reject/')
}

/**
* Messages
*
*/

Petciety.showMessageDetails = function(id) 
{ 
	if($("#message_item_" + id).hasClass('new-item')) { $("#message_item_" + id).removeClass('new-item'); }
	Petciety.showObjectDetails(id, '/ws/message_details/view'); 
}
Petciety.quickReply = function(id) 
{ 
	Petciety.showObjectDetails(id, '/ws/message_details/reply', null, null, 
		function(id) { setTimeout('Petciety.messageReply('+id+')', 500);  }
	 ); 
}
Petciety.deleteMessage = function(id, folder, job_id) 
{ 
	$('#object_row_'+ id).remove();
	$('#global_message').load('/ws/message_delete/'+id);
	$('#global_message').show();
	sort = $("#sort").val();
	sort_order = $("#sort_order").val();
	page = $("#page_num").val();
	$('#message_listing').load('/home/messages_reload/'+folder+"/"+job_id+"/"+sort+"/"+sort_order+"/"+page);
}

Petciety.toggleMessageJobDetails = function() 
{ 
	$("#message-details-job-div").toggle(); 
}
Petciety.messageReply = function(message_id, url) 
{ 
	if(!url) url = '/ws/message_reply/';
	$("#message-static").hide(); 
	$("#message-reply").load(url + message_id);
	$("#message-reply").show(); 
}
Petciety.cancelMessageReply = function(message_id) 
{ 
	$("#message-reply").hide(); 
	$("#message-static").show(); 
}
Petciety.submitMessageReply = function( formId )
{
	$("#message-static").show(); 
	$("#message-reply").hide(); 
	var _form = $("#" + formId);
	$("#" + formId).ajaxSubmit( { success: Petciety.messageReplySuccess });
}
Petciety.messageReplySuccess = function(response) 
{ 
	if($('#reply-server-response').length != 1)
	{
		$('#message-static').append('<div id="reply-server-response"></div>')
	}
	$('#reply-server-response').html(response);
	$('.action-buttons').hide();
}

/**
* Ratings
*
*/
Petciety.showRatingDetails = function(id) { Petciety.showObjectDetails(id, '/ws/rating_details'); $("#object_row_"+ id).removeClass("new-item");}
Petciety.editRating = function(id) { 
	$("#current_rating").val(id)
	Petciety.showDialog('/ws/rating_edit/' + id);  
}
Petciety.submitEditRatingForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.editRatingFormSuccess });
}
Petciety.editRatingFormSuccess = function(response) 
{ 
	var _current_id = $("#current_rating").val();
	var _score = response.substring(0, response.indexOf("#"))
	var _comment = response.substring(response.indexOf("#") + 1)
	$('#dialog').jqmHide();
	$("#rating_comment" + _current_id).html(_comment);
	$("#rating_comment" + _current_id).removeClass('overdue');
	$("#rating_score" + _current_id).html(_score);
	$("#rating_score" + _current_id).removeClass('overdue');
	$("#current_rating").val('');
}

/**
* Journals
*
*/
Petciety.showJournalDetails = function(id, left_id) 
{ 
	Petciety.showObjectDetails(id, '/ws/journal_details', "journal_entry_" + id, left_id); 
	// Remove the 'new ' flag if it exists
	$('#newFlag'+id).remove();
}

Petciety.editJournalDetails = function(id) 
{ 
	Petciety.showDialog('/ws/journal_edit/' + id); 
	
}
Petciety.submitJournalDetailsForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.journalDetailsFormSuccess });
}
Petciety.journalDetailsFormSuccess = function(response) 
{ 
	$('#dialog').jqmHide();
	$("#global_message").html(response).show();
	//$('#dueFlag'+id).remove();
	//$('.overdue').removeClass('overdue');
}
Petciety.submitJournalEditForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.journalEditSubmitSuccess });
}
Petciety.journalEditSubmitSuccess = function(response) 
{ 
	var _id = $("#journal_id" ).val()
	if( $("#date_span_" + _id).hasClass("overdue") ) $("#date_span_" + _id).removeClass("overdue"); 
	$("#action_span_" + _id).html("edit"); 
	$("#dialog_content").html(response); 
	
}

/**
* Image uploading
*
*/

Petciety.updateProfileImage = function() {  Petciety.showDialog('/ws/profile_image_update'); }
Petciety.submitProfileImageForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.profileImageFormSuccess });
}
Petciety.profileImageFormSuccess = function(response) 
{ 
	if(response.indexOf("ERROR") >= 0)
	{
		if($('#reply-server-response').length != 1)
		{
			$('#dialog_content').prepend('<div id="reply-server-response"></div>')
		}
		$('#reply-server-response').html(response.substring(6));
	}
	else
	{
		$('#dialog').jqmHide();
		$("#member-profile-image").attr("src", response); 
	}
}
Petciety.updatePetImage = function(id) {  Petciety.showDialog('/ws/pet_image_update/' + id); }
Petciety.submitPetImageForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.petImageFormSuccess });
}
Petciety.petImageFormSuccess = function(response) 
{ 
	if(response.indexOf("ERROR") >= 0)
	{
		if($('#reply-server-response').length != 1)
		{
			$('#dialog_content').prepend('<div id="reply-server-response"></div>')
		}
		$('#reply-server-response').html(response.substring(6));
	}
	else
	{
		$('#dialog').jqmHide();
		$("#pet-profile-image").attr("src", response); 
	}
}
Petciety.registrationPetImage = function() {  Petciety.showDialog('/ws/registration_pet_image'); }
Petciety.submitRegistrationPetImageForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.registrationPetImageFormSuccess });
}
Petciety.registrationPetImageFormSuccess = function(response) 
{ 
	if(response.indexOf("ERROR") >= 0)
	{
		if($('#reply-server-response').length != 1)
		{
			$('#dialog_content').prepend('<div id="reply-server-response"></div>')
		}
		$('#reply-server-response').html(response.substring(7));
	}
	else
	{
		var _member_id = $("#member_id").val();
		var _img_src = "/image/pet/full/" + _member_id + "/" +  response;
		$("#image_uuid").val(response);
		$("#pet-profile-image").attr("src", _img_src); 
		$('#dialog').jqmHide();
	}
	
	
}

Petciety.addGalleryImage = function() 
{  
	Petciety.showDialog('/ws/gallery_image_update/0');
}
Petciety.editGalleryImage = function() 
{  
	var id = $('#active_image').html();
	var _id;
	if(id && id.length > 6) 
	{
		var _numeric_id = id.substring(id.indexOf("_") + 1);
		_id = _numeric_id;
	}
	else _id = 0;
	Petciety.showDialog('/ws/gallery_image_update/' + _id); 
}
Petciety.submitGalleryImageForm = function( formId )
{
	$("#"+formId).ajaxSubmit( { success: Petciety.galleryImageFormSuccess });
}
Petciety.galleryImageFormSuccess = function(response) 
{ 
	if(response != "SUCCESS")
	{
		if($('#reply-server-response').length != 1)
		{
			$('#dialog_content').prepend('<div id="reply-server-response"></div>')
		}
		$('#reply-server-response').html(response);
	}
	else
	{
		$('#dialog').jqmHide();
		window.location.href = "/home/gallery";
	}
	
}


Petciety.editJournalDetails = function(id) {  Petciety.showDialog('/ws/journal_edit/' + id); }
Petciety.editRatingDetails = function(id) {  Petciety.showDialog('/ws/rating_edit/' + id ); }


// Method to activate the pager on a listing page
Petciety.goToPage= function( form_id, page )
{
	$("input#page_num").val(page);
	$("#"+form_id).submit();
}

// Method to set the proper sort variables and submit a listing page
Petciety.sortTable = function( form_id, sort )
{
	$("input#page_num").val(1);
	var _curr = $("input#sort").val();
	if(_curr == sort)
	{
		 var _curr_order = $("input#sort_order").val()
		 $("input#sort_order").val( _curr_order == 'asc' ? 'desc' : 'asc');
	}
	else
	{
		 $("input#sort_order").val( 'desc');
		$("input#sort").val(sort);
	}
	$("#"+form_id).submit();
}

// Method to display the proper filter in the browse pages up reload
Petciety.showBrowseFilter = function(elem)
{
	var _id = $(elem).attr('id');
	var _checks = "#" + _id + "-checks";
	var _selects = "#" + _id + "-select";
	if($(elem).hasClass('inactive-filter'))
	{
		$(elem).removeClass('inactive-filter');
		$(elem).addClass('active-filter');
	}
	else
	{
		$(elem).removeClass('active-filter');
		$(elem).addClass('inactive-filter');
		$(_checks + " input").attr('checked',false); 
		$(_selects + " select").attr('selectedIndex',0); 
	}
	$(_checks).toggle();
	$(_selects).toggle();
	
}

// Home page filtering

Petciety.reloadPublicJobs = function( filter, value, location )
{
	$('.job_filter').removeClass('active');
	$("#" + filter + "_" + value).addClass('active');
	if(filter == 'location')
	{
		if(value == 1)
		{
			if(!$('#sitting_tab').hasClass('active') ) $('#sitting_tab').addClass('active');
			$('#boarding_tab').removeClass('active');
		}
		else
		{
			if(!$('#boarding_tab').hasClass('active') ) $('#boarding_tab').addClass('active');
			$('#sitting_tab').removeClass('active');
		}
	}
	location = $('#sitting_tab').hasClass('active') ? 1 : 2;
	$("#location" + "_" + location).addClass('active');
	$("#jobs_list").load("/public/jobs/" + filter + "/" + value+ "/" + location);
	
}
Petciety.pagePublicJobs = function( page )
{
	curr_location = $("#curr_location").html();
	curr_filter = $("#curr_filter").html();
	curr_value = $("#curr_value").html();
	if(!curr_location ) curr_location = '1';
	if(!curr_filter ) curr_filter = 'all';
	if(!curr_value ) curr_value = 'all';
	$("#jobs_list").load("/public/jobs/" + curr_filter + "/" + curr_value+ "/"  + curr_location+ "/" + page);
}


Petciety.showPublicJobs = function( type )
{
	if(type == 'sitting')
	{
		if(!$('#sitting_tab').hasClass('active') ) $('#sitting_tab').addClass('active');
		$('#boarding_tab').removeClass('active');
	}
	else
	{
		if(!$('#boarding_tab').hasClass('active') ) $('#boarding_tab').addClass('active');
		$('#sitting_tab').removeClass('active');
	
	}
}

