/*          
Author Nandish@
functionality : provide search effect
                             */


var BookSortDiv = "<div id='sort' class='sortTabs'>Sort By:</div>";
    BookSortDiv += "<div id='sortPriceDiv' class='sortTabs'><a  href='#' onclick=\"sortMe('BookSortPrice')\" id='BookSortPrice'>Price</a></div>";
    BookSortDiv += "<div id='sortAlphaDiv' class='sortTabs'><a  href='#' onclick=\"sortMe('BookSortAlpha')\" id='BookSortAlpha'>Alphabetical</a></div>";
    BookSortDiv += "<div id='sortAlphaDiv' class='sortTabs'><a  href='#' onclick=\"sortMe('BookSortPublishedDate')\" id='BookSortPublishedDate'>Date Published</a></div>";

var NotesSortDiv = "<div id='sort' class='sortTabs'>Sort By:</div>";
    NotesSortDiv += "<div id='sortPriceDiv' class='sortTabs'><a  href='#' onclick=\"sortMe('NotesSortPrice')\" id='NotesSortPrice'>Price</a></div>";
    NotesSortDiv += "<div id='sortAlphaDiv' class='sortTabs'><a  href='#' onclick=\"sortMe('NotesSortType')\" id='NotesSortType'>Notes Type</a></div>";
    NotesSortDiv += "<div id='sortUniversityDiv' class='sortTabs'><a  href='#' onclick=\"sortMe('NotesSortUniversity')\" id='NotesSortUniversity'>University</a></div>";
//----------------------------------------------------------------------------------------------
//close auto suggest div when the page gets load
//-----------------------------------------------------------------------------------------------
$(function(){
   $(window).load(function() {
   $("#search_suggest_choices").hide();
	resetWidgetRadioButtons();
});
});
//--------------------------------------------------------------------------------------------------
//close autosuggest div on body click
//------------------------------------------------------------------------------------------------------
 $(function() {
    $(document).click(function() {
       $("#search_suggest_choices").hide("slow");
     });
 });
//--------------------------------------------------------------------------------------------------------
//validate search filed 
//--------------------------------------------------------------------------------------------------------
function validateSearchField() {
		searchField = $.trim($("#searchfield").val());
		searchField =  $.trim(searchField.replace('%',""));
		searchField =  $.trim(searchField.replace('_',""));
		
		if(searchField == "") {
			alert("Please enter a valid search criteria");
			$("#searchfield").focus();
			return false;
		}
		return true;
}
// ---------------------------------------------------------------------------------------
//get the cordinate value of the form filed and assign let and top values to the div tag
// ---------------------------------------------------------------------------------------

function setCordinates() {
var divObject = document.getElementById("search_suggest_choices");
var formField = document.getElementById("searchfield");
var fieldCoords = findPos(formField);
// Get the errorpanel coordinates       
var divCoords = findPos(divObject);
divObject.style.left = fieldCoords[0] + 5 + "px";
divObject.style.top = fieldCoords[1] + + 20 + "px";
}

// ---------------------------------------------------------------------------------------
//call back function to calculate position fo the form field
// ---------------------------------------------------------------------------------------
function findPos(obj) {
	var curleft = curtop = curheight = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	return [curleft,curtop];
}
//--------------------------------------------------------------------------------------------------------
//make auto search searchfield value empty on onfocus event
//--------------------------------------------------------------------------------------------------------

$(function() {
	 $(".searchfield").focus(function() {
		 $(this).val("");

	});
 });

//--------------------------------------------------------------------------------------------------------
//call ajax function get search result
//--------------------------------------------------------------------------------------------------------
$(function(){
	 $(".searchfield").keyup(function(e) {
                  
                     
               // make sure if the keyup event, arrow up key and arrow down key, dont fire ajax related stuff to
               //get result
               if(e.keyCode == 40 || e.keyCode == 38) {
                           // dont do anything
                } else {            
                   
          //ajax call for getting auto suggest result;            
	      try{
	       var searchValue = $.trim($(this).val());
	       setCordinates();

		 //make sure that the user input length is more than 3 character
      		if (searchValue.length > 3) {
			 //make auto suggest visibile if the search function call
			($("#search_suggest_choices").is(":hidden"))? $("#search_suggest_choices").show("slow") : "";
                	$.post("/autoSuggest/", {searchfield:searchValue},function(data) {
		        getSearchdata(data)});
		} else {
             
			 $("#search_suggest_choices").hide("slow",function() 
				 { $("#search_suggest_choices").html("");});
                                       
	       } // End of Else
	     } catch(e) {}
   		//if statement closed
              }
                  // main if statement closed
	       });

	});
//--------------------------------------------------------------------------------------------------------
//call back function for auto search
//--------------------------------------------------------------------------------------------------------
function getSearchdata(result) {
       if(result!= null && result!= "" ) {
		 try{
		  document.getElementById("search_suggest_choices").innerHTML = "";
                  $("#search_suggest_choices").html(result);
                  $(function() {
                      //see highlight.js file for more information 
                      highlight( 'searchfield', 'Parent','active'); 
                    });
		 } catch(e) {}
	}
}
//--------------------------------------------------------------------------------------------------------
//close autosuggest div tag while search filed lost the focus
//--------------------------------------------------------------------------------------------------------
function hideautosuggest(){
$(function() {
         $("#search_suggest_choices").hide();
	});
}
//--------------------------------------------------------------------------------------------------------
//this function  can be used to submit form when user select particular book in auto suggest div 
//by using mouse or by using arrow keys
//--------------------------------------------------------------------------------------------------------
function subForm(subvalue,flag) {
    textField = document.getElementById("searchfield");
	flagFiled = document.getElementById("distinct");
	if(textField.value!= "") {
         textField.value = "";
		 repsubvalue = subvalue.replace("<b>","");
		 repsubvalue1 = repsubvalue.replace("</b>","");
         textField.value = repsubvalue1;
		 flagFiled.value = flag;
         document.forms['search-form'].submit();
		 return true;
	} 
}
//--------------------------------------------------------------------------------------------------------
//validate user backpack when both radio buttons (buy and rent) displayed
//--------------------------------------------------------------------------------------------------------

function validateBoth(formBoth) {
    rentRadio = formBoth.rent[0];
	sellRadio = formBoth.rent[1];
    if(!rentRadio.checked && !sellRadio.checked) {
		alert("Please select  a radio buttons to Rent or Buy")
			return false;

	}

     if (rentRadio.checked) {
		       if(formBoth.toggleRadio[0].checked){
                   formBoth.type.value = "f_rental_semester";
		        }
				if(formBoth.toggleRadio[1].checked){
                   formBoth.type.value = "f_rental_quarter";
		        }
				if(formBoth.toggleRadio[2].checked){
                   formBoth.type.value = "f_rental_summer";
		        }
		 
     }
          
     if (sellRadio.checked) {
		 formBoth.type.value = "SELL";
		 
     }
  }
//--------------------------------------------------------------------------------------------------------
//validate user backpack when Rent radio button displayed
//--------------------------------------------------------------------------------------------------------

function validateRent(formRent) {
	    if(formRent.toggleRadio[0].checked) {
                   formRent.type.value = "f_rental_semester";
		        }
	   if(formRent.toggleRadio[1].checked) {
                   formRent.type.value = "f_rental_quarter";
	        }
	  if(formRent.toggleRadio[2].checked) {
                   formRent.type.value = "f_rental_summer";
	        }
                return true;
 }
//--------------------------------------------------------------------------------------------------------
//validate user backpack when buy radio button displayed
//--------------------------------------------------------------------------------------------------------

function validateSell(formSell) {
                formSell.type.value = "SELL";
                return true;
}


//--------------------------------------------------------------------------------------------------------
//show price span tag when the user toggle radio buttons
//--------------------------------------------------------------------------------------------------------
 function showPrice(obj,divprice,datevalue,animatediv){ 

		   togglePrice = obj.value;

             var ulTagId = $(obj).parents().get(1).id;

			 resetMyWidget(ulTagId);

			 
			 $("#" + ulTagId).find("input").each(function() {
			  if($(this).is(":checked")) {
			        $(this).next().css({"visibility":"visible"});
			     }
			  });


		
		
		   $("#" + divprice).html("");
		   $("#" + divprice).html(togglePrice);
		
			$("#" + animatediv).animate({
            "height": "toggle", "opacity": "toggle"
             }, { duration: "slow" });

		     $("#" + animatediv).animate({
            "height": "toggle", "opacity": "toggle"
             }, { duration: "slow" });
			 
          }
//--------------------------------------------------------------------------------------------------------
//submit form when the user click particualt book image in the search result page
//--------------------------------------------------------------------------------------------------------
 function showBookDetails(bookid) {
	 var bookidobj = document.getElementById('book_id')
		 if(bookid!= ""){
		   bookidobj.value = parseBoldtag(bookid);
		   document.forms['book-form'].submit();
	 }
 }


//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
 function showEditBook(bookid) {
	 var bookidobj = document.getElementById('bookid')
		 if(bookid!= "") {
		     bookidobj.value = parseBoldtag(bookid);
		   document.getElementById("edit-form").submit();
	 
	 }
 }

//--------------------------------------------------------------------------------------------------------
//hide Rent div when the user click rent sell or buy button
//--------------------------------------------------------------------------------------------------------
 arr = new Array();
 function hideRentdiv(ulTagId,sellingPrice,divprice,bpackid) {
	 document.getElementById(ulTagId).style.visibility = "hidden";
		/*$(".bookAvailabilityResultUl1 li :input:not(:checked) ~ span.dueDate").css("visibility","hidden");
		 $(".bookAvailabilityResultUl2 li :input:not(:checked) ~ span.dueDate").css("visibility","hidden");
		$(".bookAvailabilityResultUl1 li :input:checked ~ span.dueDate").css("visibility","hidden");
		 $(".bookAvailabilityResultUl2 li :input:checked ~ span.dueDate").css("visibility","hidden");*/

		 $("#" + ulTagId).find("span").each(function() {
			 $(this).css({"visibility":"hidden"})
			});


		//resetMyWidget(ulTagId);

   //hideRentDiv function can be used to two places 1,search results and 2 is backpack so
   // in search result we get backpack id is undefined ,so don't execute this piece of code

    if(bpackid != undefined) {
	waitMessage();
    url = "/index.php/csearch/updateBackPackRentaltype/"; 
	var selltype = "SELL";
	var bppackid = bpackid;
      $.post(url,{backpackid:$.trim(bppackid),stype:$.trim(selltype)},function(result){
		    if(result == "1") {
			  showBackPack();
			  unblock();
		   }
	});
	}

	 arr.pop();
	 arr.push($("#"+divprice).html())
	 $("#"+divprice).html("");
	 $("#"+divprice).html(sellingPrice);



 }
//--------------------------------------------------------------------------------------------------------
//show Rent div when the user click rent  button
//--------------------------------------------------------------------------------------------------------
function showRentdiv(ulTagId,divprice) {
    document.getElementById(ulTagId).style.visibility = "visible";
    $("#"+divprice).html("")
	  $("#" + ulTagId).find("input")
		       .each(function() {
		        var checked = $(this).is(":checked");
				 if(checked){   
					   $("#"+divprice).html($(this).val());
					   $(this).next().css({"visibility":"visible"});
				                
	             }
			});
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
function updateBackPack(obj,divprice,type,bpackidvalue){
	togglePrice = obj.value;

           
            
		   $("#" + divprice).html("");
		   $("#" + divprice).html(togglePrice);

//	showPrice(obj,divprice)
    waitMessage();
    url = "/index.php/csearch/updateBackPackRentaltype/"; 
    $.post(url,{backpackid:$.trim(bpackidvalue),stype:$.trim(type)},function(result){
		    if(result == "1") {
			  showBackPack();
			  unblock();
		   }
	});

	
	
}
//------------------------------------------------------------------------------------------------
function resetWidgetRadioButtons() {
		$(".bookAvailabilityResultUl1 li :input:not(:checked) ~ span.dueDate").css("visibility","hidden");
		 $(".bookAvailabilityResultUl2 li :input:not(:checked) ~ span.dueDate").css("visibility","hidden");
		$(".bookAvailabilityResultUl1 li :input:checked ~ span.dueDate").css("visibility","visible");
		 $(".bookAvailabilityResultUl2 li :input:checked ~ span.dueDate").css("visibility","hidden");

}
// --------------------------------------------------------------------------------------------------------------
function notifyAvailability(isbn) {

	url = "/notify-availability";
	
//{ name: "John", time: "2pm" }	
	
	 val = "none";
	 if ($("#notify_rent" + isbn + ":checked").val() != undefined)
	 {
		 	val = "notify_rent";
	 }

	 if ($("#notify_sell" + isbn + ":checked").val() != undefined)
	 {
		 	val = "notify_sell";
	 }

 	 if (($("#notify_sell" + isbn + ":checked").val() != undefined) &&  ($("#notify_rent" + isbn + ":checked").val() != undefined)) {
		    val = "notify_both";
	 }

	 if (val == "none")
	 {
		 alert("Please select a notification option");
		 return false;
	 }

	url += "/" + isbn + "/" + val;

    $.get(url,function (response) {
		switch (response) {
			case "DUPLICATE":
				alert("You are already registered for this notification. You will be notified when this book becomes available.");
				break;
			case "INFORMATION_SAVED":
				alert("Thank You! You will be notified when this book becomes available.");
			    break;
			case "ERROR":	
				break;
			default:
				alert("Thank You! Please logon to Silibi. After successful logon, you will be notified when this book becomes available.");
				window.location.href = response;
			    break;

		}
	});

}
// --------------------------------------------------------------------------------------------------
function addBook(isbn) {
  url = "/list-my-book/" + isbn;
  window.location.href=url;
}


// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
function parseBoldtag(bookid) {
	if(bookid!= "") {
		 repsubvalue = bookid.replace("<b>","");
		 repsubvalue1 = repsubvalue.replace("</b>","");
         return repsubvalue1;
		
        
	} 
}
// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
function showtip() {
			document.getElementById("getTip").style.visibility="visible";				
			return true;
		}
// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
function hideSearchTips() {
			 document.getElementById("getTip").style.visibility="hidden";
			 return true;
		}
// --------------------------------------------------------------------------------------------------
$(function() {

        initializeTabs();
	///re-initialize the tab clicks
        $("#bookTab").click(function() {
	   setBooksTab();
	   if(!validateSearchField())
			return false;
	   $("#sortType").val("ASC");
 	   sortMe("BookSortPrice");
        });

        $("#notesTab").click(function() {
	   setNotesTab();
	   if(!validateSearchField())
			return false;
	   $("#sortType").val("ASC");
 	   sortMe("NotesSortPrice");
        });

});
// --------------------------------------------------------------------------------------------------
function setSortField(elementName) {
  
  $("#sortField").val(elementName);
  if ($("#sortType").val() == "ASC") {
	img = "/images/arrowDown.gif"; 
  }
  else {
	img = "/images/arrowUp.gif";
  }
//close auto suggest div when the page gets load
  resetArrow(elementName); 

  switch (elementName) {
   case "BookSortPrice":
		$("#"+elementName).html("Price <img style='border:0px' src='" + img + "' />");
		break;
   case "BookSortAlpha":
		$("#"+elementName).html("Alphabetical <img style='border:0px' src='" + img + "' />");
		break;
   case "BookSortPublishedDate":
		$("#"+elementName).html("Published Date <img style='border:0px' src='" + img + "' />");
		break;
   case "NotesSortPrice":
		$("#"+elementName).html("Price <img style='border:0px' src='" + img + "' />");
		break;
   case "NotesSortType":
		$("#"+elementName).html("Notes Type <img style='border:0px' src='" + img + "' />");
		break;
   case "NotesSortUniversity":
		$("#"+elementName).html("University <img style='border:0px' src='" + img + "' />");
		break;
  }

}
// --------------------------------------------------------------------------------------------------
function sortMe(elementName) {
   $("#sortField").val(elementName);

   if ($("#sortType").val() == "ASC") 
	$("#sortType").val("DESC");
   else
	$("#sortType").val("ASC");
/*	
   alert($("#tabField").val());
   alert($("#sortField").val());
   alert($("#sortType").val());
*/
  document.forms['search-form'].submit();
  return true;
}
// --------------------------------------------------------------------------------------------------
function resetArrow(elementName) {
  $("#BookSortPrice").html("Price");
  $("#BookSortAlpha").html("Alphabetical");
  $("#BookSortPublishedDate").html("Published Date");
  $("#NotesSortPrice").html("Price");
  $("#NotesSortType").html("Notes Type");
  $("#NotesSortUniversity").html("University");
}
// --------------------------------------------------------------------------------------------------
 function initializeTabs() {
/*
   alert($("#tabField").val());
   alert($("#sortField").val());
   alert($("#sortType").val());
*/
   if ($("#tabField").val() == "BOOKS") {
	setBooksTab();	
   }
   if ($("#tabField").val() == "NOTES") {
	setNotesTab();	
   }

 }
// --------------------------------------------------------------------------------------------------
function setBooksTab() {
 	  //$("#bookTab").css("background-image","url(/images/BooksActiveTab.jpg)");
      //$("#notesTab").css("background-image","url(/images/NotesInactiveTab.jpg)");
		   $("#bookTab").css({"background-color":"#A3D74F"});
           $("#notesTab").css({"background-color":"lightgrey"});
           $("#tabField").val('BOOKS');
           $("#sortDiv").html(BookSortDiv);

	   setSortField($("#sortField").val());
}
// --------------------------------------------------------------------------------------------------
 function setNotesTab() {
	   //$("#notesTab").css("background-image","url(/images/NotesActiveTab.jpg)");
	   //$("#bookTab").css("background-image","url(/images/BooksInactiveTab.jpg)");
	   $("#notesTab").css({"background-color":"#A3D74F"});
       $("#bookTab").css({"background-color":"lightgrey"});
	   $("#tabField").val('NOTES');
	   $("#sortDiv").html(NotesSortDiv);

	   setSortField($("#sortField").val()); 

  }
// --------------------------------------------------------------------------------------------------
function viewpages(noteid) {
	if(noteid!="" && noteid!=null) {
		$("#note_id").val(noteid);
	}
     document.getElementById('notes-form').submit();
}
// --------------------------------------------------------------------------------------------------
function resetMyWidget(ulTagId) {
		$("#" + ulTagId + " li :input:not(:checked) ~ span.dueDate").css("visibility","hidden");
		 $("#" + ulTagId + " li :input:not(:checked) ~ span.dueDate").css("visibility","hidden");
		$("#" + ulTagId + " li :input:checked ~ span.dueDate").css("visibility","visible");
		 $("#" + ulTagId + " li :input:checked ~ span.dueDate").css("visibility","hidden");
}

