/**
 * @uses lib/Prototype/Prototype.js
 * @uses lib/Sureflix/Sureflix.js
 * @uses lib/Utilities/Utils.js
 * @uses lib/Localization/Localization.js
 */  
  
 /** declared in ClientServerBridge:
 * var SmartCompareCriteria = "rating,yourrating,year"; 
 * var SmartCriteriaAsTextbox = "title,phrase,star";
 */

// hack to fix the width of SmartSelect1 in Safari
Sureflix.Plugins.Detector.detectBrowser();
if (Sureflix.Plugins.Detector.browser == "Safari") {
	document.writeln('<style>\n');
	document.writeln('	.SearchFilters .SmartSelect1 { width: 135px; }\n');
	document.writeln('	.PPMSearchFilters .SmartSelect1 { width: 115px; }\n');
	document.writeln('</style>\n');
}
 
/**
* Submits the form
*/
function SubmitSearchForm(ctr) {
	if ($F(ctr)) {
		$('SureBtnAnchorSearchBtn').onclick();
	}
}

/**
 *	Make details combo visible and call webservice to populate it
 *	@param {Element} criteria The select combo with the criteria
 */
function ShowNarrowFieldCondition(criteria)
{
	var criteriaVal = criteria.value;
	var ind = criteria.id.replace("narrowField_","");
	var comboLt = $("narrowValueCombo_" + ind);
	var comboRt = $("narrowCompare_" + ind);
	var txtbx = $("narrowValueTxtbx_" + ind);
	var lang = "en";
	try{
		lang = Sureflix.Localization.getLang();
	} catch(e) {
		Sureflix.Error.ErrorHandler.consoleError(e);
		lang = "en";
	}
	
	var typedVal = "";
	if (txtbx != null){
		typedVal = txtbx.value;
	}
	
	//select one case
	if (criteriaVal == "") {
		if (txtbx) txtbx.style.display = "none";
		if (comboLt) comboLt.style.display = "none";
		if (comboRt) comboRt.style.display = "none";
	//combo case
	} else if (SmartCriteriaAsTextbox.indexOf(criteriaVal.toLowerCase()) == -1)	{
		//hide textbox
		if(txtbx != null){
			txtbx.className = "SmartInput";
			txtbx.style.display = "none";
		}			

		//compare case
		if (SmartCompareCriteria.indexOf(criteriaVal.toLowerCase()) > -1){
			GetDataUsingAjax(comboRt, criteriaVal, typedVal, ind, lang);
			comboRt.className = "SmartShort";
			comboRt.style.display = "";
			if (criteriaVal.toLowerCase() != "year"){
				GetDataUsingAjax(comboLt, criteriaVal, typedVal, ind, lang);					
				comboLt.className = "SmartShort";
				comboLt.style.display = "";
			}else{				
				txtbx.value = "";
				txtbx.className = "SmartShort";
				txtbx.style.display = "";
				comboLt.style.display = "none";
			}
		//single combo case
		}else{
			GetDataUsingAjax(comboLt, criteriaVal, typedVal, ind, lang);
			comboLt.className = "SmartSelect2";
			comboLt.style.display = "";
			comboRt.style.display = "none";
			txtbx.style.display = "none";
			comboLt.focus();
		}
	//textbox case
	} else {
		//show textbox
		if(txtbx != null){			
			txtbx.className = "SmartInput";
			comboRt.style.display = "none";
			txtbx.style.display = "";
			txtbx.focus();
			txtbx.select();//txtbx.value = ""; //Oct 19,2007 Geanina: retain value and highlight text
		}
		//hide combo
		if(comboLt != null){
			comboLt.className = "SmartSelect2";
			comboLt.style.display = "none";
		}
	}
}

/**
*	Use webservice to retrieve data and populate the combos
*	@param {Element} comboLt the left values combo object
*	@param {String} criteriaVal the criteria selected
*	@param {Int} index the index of the row
*	@param {String} lang the language we want the combo box options to be translated to
*/
function GetDataUsingAjax(comboLt, criteriaVal, selVal, index, lang)
{
	lang = lang || "en";
	
	var movieZone = Sureflix.getMovieZone();
	var comboRt = $(getSmartSelectID("Compare", index)); 
	comboLt = $(comboLt);
	var xml = top.Sureflix.Localization.getKeyValueData(criteriaVal, movieZone, lang, Sureflix.currentTagZone);

	var isRating = (criteriaVal.toLowerCase().indexOf("rating") > -1);
	
	//call webservice twice, once for the operators and second for the rating values
	if (isRating) {
		comboLt = comboRt;
		var xratingXml = top.Sureflix.Localization.getKeyValueData("xrating", movieZone, lang, Sureflix.currentTagZone);
		// rating doesn't need any initial operators
		Sureflix.UI.SelectUtils.fillSelectBoxWithKeyValueXml(getSmartSelectID("ValueCombo", index), xratingXml, selVal);
	}

	var initialOptions = getInitialOptions(criteriaVal); 
	var useCompareCombo = (criteriaVal == "Year" || isRating);
	var comboID = getSmartSelectID((useCompareCombo ? "Compare" : "ValueCombo"), index);

	Sureflix.UI.SelectUtils.fillSelectBoxWithKeyValueXml(comboID, xml, selVal, initialOptions);	
			
	if(comboLt.selectedIndex < 0 || (selVal == "" || (comboLt[comboLt.selectedIndex].value.toLowerCase() != selVal.toLowerCase())) )	{
		comboLt.selectedIndex = 0;
	}
}

/**
*	Creates the object used by Sureflix.UI.SelectUtils.fillSelectBoxWithKeyValueXml to create any initial select box options
*	@param {String} criteriaVal the criteria selected
*   @return {Object} The inital options object expected by Sureflix.UI.SelectUtils.fillSelectBoxWithKeyValueXml
*/
function getInitialOptions(criteriaVal) {

    var initialOptions = [];
    var i = 0;
    criteriaVal = criteriaVal.toLowerCase();
    
    switch(criteriaVal) {
        case 'category': 
        case 'studio':
        case 'director':  
        case 'theme':  
        case 'content':  
        case 'men':  
        case 'country':  
            initialOptions[i] = { value: '', text: top.Sureflix.Localization.getPhrase('SelectOne+') }; 
            break;
    }
    
    i++;
    
    switch (criteriaVal) {
        case 'category':
            initialOptions[i] = { value: 'All', text: top.Sureflix.Localization.getPhrase('All') };
            break;
    }
    return initialOptions;
}

/**
*	Gets the name of the smartselect
*	@param {string} comboType the type of combo
*/
function getSmartSelectName(comboType) {
    return "narrow" + comboType;
}

/**
*	Gets the ID of the smartselect
*	@param {string} comboType the type of combo
*	@param {int} index the index of the search filter
*/
function getSmartSelectID(comboType, index) {
    return "narrow" + comboType + "_" + index;
}

/**
*	Insert an item to the top of the Values Combo. e.g. Select One, All
*	@param {string} topTxt the text to show up in the combo
*	@param {string} topVal the text to show up in option value of the combo
*	@param {obj} comboObj the obj to append the value to
*	@return {void}
*	@author 12/21/2007 Geanina
*/
function AddComboTopVal(topTxt, topVal, comboObj)
{
	var option = new Option(topTxt, topVal);	
	if (comboObj.options.add) {
		comboObj.options.add(option,0);
	} else {
		comboObj.insertBefore(option,comboObj.options[0]);
	}
}

/**
 *	Reset form by removing search criteria, hiding narrow criteria and emptying the first line.
 *	@param {string} searchType Type of search (category, theme, studio, etc.)
 *	@return {void}
 *	@author Erik 09/18/2008
 */
function NewSearch(searchType)
{
	if (!searchType) searchType = "Phrase";
	
	$('narrowValueTxtbx_0').value = "";
	hideNarrow();
	
	var tableBody = $('narrowFilters').childElements().first();
	var firstRow = tableBody.childElements().first();
	var buttonRow = tableBody.childElements().last();
	var hrRow = $('NarrowYourSearchBar');
	var narrowRow = $('NarrowYourSearchBar').nextSiblings().first();

	var deleteEle = function(e) {
		if ( (e !== firstRow) && (e !== hrRow) && (e !== buttonRow) && (e !== narrowRow) ) {
			Element.remove(e);
		}
	}
	tableBody.childElements().each(deleteEle);
	
	var firstSelect = $('narrowField_0');
	firstSelect.value = searchType;
	ShowNarrowFieldCondition(firstSelect);
	if ($('narrowValueCombo_0').isDisplayed()) {
		$('narrowValueCombo_0').focus();
	} else if ($('narrowValueTxtbx_0').isDisplayed()) {
		$('narrowValueTxtbx_0').focus();
	}
	
  	if (window.myStack){  
 		myStack.sizeCollapsers();
 	}
}
	
/** 
 *	Goes back in the browser history
 *	@return {void}
 *	@author Erik 07/09/2008
 */
function SearchBack()
{
	DisplayIsLoading();
	var f = document.thisForm;
	var action = "?Navigate=Back";

	f.action = action;
	f.submit();
}
	
/**
*	Adds a new criteria row before the buttons row
*	@param {Int} index The position for the new row	
*   @return {void}  	
*/
function AddCriteriaRow(index)
{

	//Gets the body of the table
    var table = $$('#narrowFilters tbody')[0];
    //Gets the first row
	var firstRow = table.childElements().first();
	
	//Creates a new row in the proper place (index)
	var row = $('narrowFilters').insertRow(index+1);
	row.style.display = "none";
	
    //Add two cells in the row, modify the id of each cell
	var cell1 = row.insertCell("0");
	cell1.id = "narrowCell1_" + index;
	var cell2 = row.insertCell("1");
	cell2.id = "narrowCell2_" + index;
		
	//Copy the content of the firstRow into each cell.
	cell1.innerHTML = firstRow.cells[0].innerHTML;
	cell2.innerHTML = firstRow.cells[1].innerHTML;	

    //Make sure we select the first item in the combo box for the first cell
    var setControlsInCell1 =  function(e){
          if(e.tagName == "SELECT" ){
            e.selectedIndex = 0;
            e.id = "narrowField_" + index;
          }
    }
	$(cell1).childElements().each(setControlsInCell1);

    //Make sure we select the first item in each combo box, we delete any text in the input text box and we update the id of all elements
    //We also hide all form elements and display the span tag
    var setControlsInCell2 = function(e){   
          //if(e.tagName == "SPAN" ){
          //  e.id = "narrowTextMsg_" + index;
          //  $(e).show();
          //}else{
            $(e).hide();
            if(e.tagName == "SELECT" ){
              if (e.className == "SmartSelect2"){
                e.id = "narrowValueCombo_" + index;
              }else if (e.className == "SmartShort"){
                e.id = "narrowCompare_" + index;
              }
              e.selectedIndex = 0;
            }
            if(e.tagName == "INPUT" ){
              e.value = '';
              e.id = "narrowValueTxtbx_" + index;
            }            
          //}
    } 
	$(cell2).childElements().each(setControlsInCell2);
	
	row.style.display = "";
}	
	
/**
 * This function is called when data is entered or modified in the criteria field
 * @param {Element} ctr The element where we are entering data into (or deleting data from)
 * @return {void}   	 
 */
 function ShowNextRow(ctr)
 {
	if (SearchIsLoading()) return;
	
	var index = (ctr.id.replace(ctr.name+"_","")*1) + 1;
	var ctrValue = ctr.value.replace(/ /g, "").replace(/\\n/g, "");

	if ($('narrowFilters').rows.length == (index+2) && (ctr.value.length > 0) ) {
		AddCriteriaRow(index);
	} else if ( ($('narrowFilters').rows.length == (index+3)) && (ctr.value.length == 0) ) {
		Element.remove($('narrowFilters').rows[index+1]);
	}

 	if (window.myStack) {  
 		myStack.sizeCollapsers();
 	}
}

 /**
 * Returns true if a search is currently loading
 */ 
 function SearchIsLoading(){
	return $('LoadingSearch').isDisplayed();
 }

 /**
 * Displays is loading message and graphic
 */ 
 function DisplayIsLoading(){
	$('SureBtnAnchorSearchBtn').hide();
	$('LoadingSearch').show();
 }

 /**
 * This method is called when one clicks the submit button	 
 * @return {void}   
 */    	 
 function DoSearch()
 {	  
	  DisplayIsLoading();
	  var f = document.thisForm;
	  var table = $$('#narrowFilters tbody')[0];
	  var Fields = "";
	  var Values = "";
	  var isValidForm = true;
	  var valueToCheck = "";
     
      var isValidValue = function(col,val){
		var tempVal = val.replace("\|","").toLowerCase();		
		tempVal = removeComparisonOperators(tempVal);		
		isValidForm = ValidateSmartForm(tempVal,col);
		return isValidForm;
      }
            
      var buildQuery = function(e){
        //We need to have two cells
        if (e.cells.length  == 2){
            var cmb = $(e.cells[0]).childElements().first();
            if (cmb){
              var val = $F(cmb);
              if (val){
                
                valueToCheck = buildValues(e);
                //We check that we have a value entered and we validate that is a valid value
                if (valueToCheck && isValidValue(val,valueToCheck) ){
					Fields += (Fields ? "|" : "") + val;
					Values += (Values ? "|" : "") + valueToCheck;
                }                
              }
            }
        }
      }
      
      var buildValues = function(e){
		var tmpVal = "";
		$(e.cells[1]).childElements().each(function(x){
			if (x.style.display !== "none"){
			  if (x.tagName == "INPUT" || x.tagName == "SELECT"){
				tmpVal += $F(x);
			  }
			}
		});
		if (removeComparisonOperators(tmpVal).length > 0 ){
		    return tmpVal.replace('+', '_');
		} else {
			return "";
		}
      }
      table.childElements().each(buildQuery);

      //Oct 18, 2007 Geanina: added Find to the QS
      var action = "?Page=1&Find=" + (GetQSParam("Find") == "" ? "Movies" : GetQSParam("Find"));
      action += "&Fields=" + Fields + "&Values=" + Values;

	  if (isValidForm){
		  f.action = action; 		
		  f.submit(); 
	  }
 }

/**
*	This function validates the smartsearch form when the Submit button is clicked. 
*	So far, there is a validation for Year only (textbox value is a 4 digits number).
*	@author 10/17/2007 Geanina
*	@param {String} ctr The control where to make the validation.
*   @param {String} type The type of validation e.g. year 
*	@return {boolean}	
*/
function ValidateSmartForm(ctr, type)
{
	var isValid = true;
	switch (type.toLowerCase()) {	
		case "year":
			if (ctr != ""){
				isValid = IsValidYear(ctr);
			}
			break;
	}
	return isValid;
}
	
/**
*	validate the textbox
*	@author 10/17/2007 Geanina
*	@param {String} txtbx 4 character value
*	@return {boolean}	
*/
function IsValidYear(txtbx)
{
	var reNonDigit = new RegExp("\D{1,}","ig"); //any non digit
	var reFourDigit = new RegExp("^[12]{1}[0-9]{3}$","ig");
	var isValidYear = true;				
	if (txtbx.search(reNonDigit) > -1 || txtbx.search(reFourDigit) == -1){ //no match means -1
		isValidYear = false;
		alert(jsEnterValidYear);
	}
	return isValidYear;
}

/**
* Shows the narrow your search rows
*/
function toggleNarrow(){
	if ($('NarrowBullet').className.indexOf('SureSearchNarrowBullet_sel')) {
		showNarrow();
	} else {
		hideNarrow();
	}
	
	if (window.myStack){  
		myStack.sizeCollapsers();
	}	
}

/**
 *	Hides Narrow Your Search options
 */
function hideNarrow() {
	var i=0;
	$('NarrowYourSearchBar').nextSiblings().each(function(e) {
		if (i==0) {
			e.hide();
		} else if (e.id !== "NarrowSearchButtons") {
			e.remove();
		}
		i++;
	});
	
	clearNarrowOne();
	
	$('NarrowBullet').className = 'SureSearchNarrowBullet';
}

/**
 *	Displays Narrow Your Search options
 */
function showNarrow() {
	clearNarrowOne();
	
	$('NarrowYourSearchBar').next().show();
	
	$('NarrowBullet').className ='SureSearchNarrowBullet_sel';
	
	$('NarrowYourSearchBar').next().down('.SmartSelect1').focus();
}

/**
 *	Resets the first row of Narrow Your Search
 *	@author Erik 9/18/2008
 */
function clearNarrowOne() {
	var smartInput = $('NarrowYourSearchBar').next().down('.SmartInput');
	smartInput.value = "";
	
	var smartSelect = $('NarrowYourSearchBar').next().down('.SmartSelect1');
	smartSelect.selectedIndex = 0;
	smartSelect.onchange();
}


/**
*	gets the regex used for comparison operators
*	@author 10/20/2008 Amy
*	@return {Object} The regext
*/
function getComparisonOperatorRegex(){
	return new RegExp(/(equal(~*)to|greater(~*)than|less(~*)than)/ig);
}

/**
*	checks if the passed text contains any comparison operators
*	@author 10/20/2008 Amy
*	@param {String} text The text to check
*	@return {boolean}	
*/
function containsComparisonOperators(text){
	var tempText = text.replace(" ", "~");
	var regex = getComparisonOperatorRegex();
	
	return regex.test(tempText);
}

/**
*	removes any comparison operators from the text
*	@author 10/20/2008 Amy
*	@param {String} text The text to replace
*	@return {String} The replaced text
*/
function removeComparisonOperators(text){
	var returnText = text;
	if(containsComparisonOperators(text)){
		var regex = getComparisonOperatorRegex();
		returnText = text.replace(" ", "~").replace(regex, "").replace("~", " ");
	}
	return returnText;
}

