﻿/* 
 *	Create namespaces
 */
TspScript = { }
TspScript.UI = { }

/* 
 *	Toggle element display functionality
 *	- Use this functionality to toggle the display of a panel between none and block.
 *	Usage:
 *	TspScript.UI.ToggleElementDisplay(true, 'divId');
 */
TspScript.UI.ToggleElementDisplay = function(hide, elementId) {
	if(hide) {
		document.getElementById(elementId).style.display = 'none';
	}else{
		document.getElementById(elementId).style.display = 'block';
	}
}



TspScript.SearchPopup = {
	Initialize : function(searchButtonId, textBoxId, resultsPanelId, currentCulture, delay, maxResults) {
		TspScript.SearchPopup.__searchButtonId = searchButtonId;
		TspScript.SearchPopup.__textBoxId = textBoxId;
		TspScript.SearchPopup.__resultsPanelId = resultsPanelId;
		TspScript.SearchPopup.__currentCulture = currentCulture;
		TspScript.SearchPopup.__delay = delay;
		TspScript.SearchPopup.__maxResults = maxResults;
		var resultContainerPanel = document.getElementById(TspScript.SearchPopup.__resultsPanelId)
		resultContainerPanel.style.display = 'none';
		
		Creative.Waad.Events.AddEvent(document, 'click', 
		function() {
			var resultContainerPanel = document.getElementById(TspScript.SearchPopup.__resultsPanelId);
			if(resultContainerPanel){
				resultContainerPanel.style.display = 'none';
			}
		});
	},
	SearchButtonClick : function(e, searchQs) {
        Creative.Waad.ExitPopup.InternalLink();
        var evt = (e) ? e : window.event;
        var key = (evt.keyCode) ? evt.keyCode : evt.which;
        if(key == 13) {
            if( e.preventDefault ) {
                e.preventDefault(); 
            }
            e.returnValue = false;
            
            __doPostBack(TspScript.SearchPopup.__searchButtonId,'');
        }
    },
    GetQuickSearchResult : function() {
		var resultContainerPanel = document.getElementById(TspScript.SearchPopup.__resultsPanelId)
		var queryTextbox = document.getElementById(TspScript.SearchPopup.__textBoxId).value;

		//Remove spaces from input
		var tTrimmedQuery = queryTextbox;
		tTrimmedQuery = tTrimmedQuery.replace(/^\s+/,''); 
		tTrimmedQuery = tTrimmedQuery.replace(/\s+$/,'');
		while(tTrimmedQuery.indexOf('  ') > 0)
			tTrimmedQuery = tTrimmedQuery.replace('  ', ' ');
		
		var handleSetTimeout = null;

		if (tTrimmedQuery.length >= 2 && queryTextbox != '') {
			var tFirstTwo = tTrimmedQuery.substr(0, 2);
			if (tFirstTwo == TspScript.SearchPopup.__currentInputChars) {
				// We already have the right list of results, just filter and show them
				TspScript.SearchPopup.__showQuickSearchResult(TspScript.SearchPopup.__resultObject);
			} else {
				// Otherwise fetch the new list from the database
				Tsp.Website.WebServices.AjaxRequests.GetSearchResult(tFirstTwo, TspScript.SearchPopup.__currentCulture, TspScript.SearchPopup.__quickSearchSuccess, TspScript.SearchPopup.__quickSearchFailed, tFirstTwo);
			}
		} else {
			//Hide results
			if(resultContainerPanel) {
				resultContainerPanel.style.display = 'none';
			}
		}
	},
	
	__quickSearchSuccess : function(result, context) {
		TspScript.SearchPopup.__currentInputChars = context;
		TspScript.SearchPopup.__resultObject = result;
		TspScript.SearchPopup.__showQuickSearchResult(TspScript.SearchPopup.__resultObject);
	},
	__quickSearchFailed : function() {
		var resultContainerPanel = document.getElementById(TspScript.SearchPopup.__resultsPanelId);
		if(resultContainerPanel) {
			resultContainerPanel.style.display = 'none';
		}
	},
	
	
	
	__showQuickSearchResult : function(result) {
		var resultContainerPanel = document.getElementById(TspScript.SearchPopup.__resultsPanelId); 
		var queryTextbox = document.getElementById(TspScript.SearchPopup.__textBoxId).value;
		queryTextbox = queryTextbox.replace(/^\s+/,''); 
		queryTextbox = queryTextbox.replace(/\s+$/,'');
		while(queryTextbox.indexOf('  ') > 0)
			queryTextbox.replace('  ', ' ');

		var filteredObject = new Array();
		//Check if result producttitle or keywords contains the current queryTextbox text
		for (i=0;i<result.length;i++){
			if(result[i].ProductTitle.toLowerCase().indexOf(queryTextbox.toLowerCase())!=-1 || result[i].Keywords.toLowerCase().indexOf(queryTextbox.toLowerCase())!=-1 ){
				filteredObject.push(result[i]);
			}
		}
		result = filteredObject;

		//Reset the nodes in the container
		TspScript.SearchPopup.__resetElementNodes(resultContainerPanel);
		if (result.length == 0) {
			resultContainerPanel.style.display = 'none';
			return;
		} else
			resultContainerPanel.style.display = '';



		//Create div elements for result popup
		var divResultContainer = null;
		var divResultHeader = null;
		var imageElement = null;
		var aResultItemElement = null;
		var descriptionText = null;
		var divImageElement = null;
		var divDescriptionElement = null;
		var resultCount = 0;
		var resultHeaderText = null;
		var divClear = null;

		if(result && resultContainerPanel) {
			if(result.length > TspScript.SearchPopup.__maxResults) {
				resultCount = TspScript.SearchPopup.__maxResults;
			} else {
				resultCount = result.length;
			}
			// Header with search results count
			if(resultCount > 0) {
				divResultHeader = document.createElement('h1');
				divResultHeader.setAttribute('ID','qs_result_header');
				resultContainerPanel.appendChild(divResultHeader);
			}
			divResultContainer = document.createElement('div');
			divResultContainer.setAttribute('ID','qs_result_container');
			Creative.Waad.Css.AddClassToElement(divResultContainer, 'tsp-results');
			resultContainerPanel.appendChild(divResultContainer);

			//Search result items
			var tUrl = null;
			for (i=0;i<resultCount;i++){
				//add quick search query text to Url
				tUrl = result[i].ProductPageUrl + '&qs=' + queryTextbox;

				aResultItemElement = document.createElement('a');
				aResultItemElement.setAttribute('ID','qs_result_' + i);
				divResultContainer.appendChild(aResultItemElement);
				eval('var tFunc = function() { document.location=\'' + tUrl + '\' ;}');

				Creative.Waad.Events.AddEvent(aResultItemElement, 'click', tFunc);
				Creative.Waad.Css.AddClassToElement(aResultItemElement, 'tsp-results-item');

				//Image element of result item
				divImageElement = document.createElement('div');
				imageElement = document.createElement('img');
				divImageElement.appendChild(imageElement);
				if(result[i].ImageUrl){
					imageElement.src = result[i].ImageUrl;
					Creative.Waad.Css.AddClassToElement(imageElement, 'tsp-img-item');
				} else {
					imageElement.src = 'http://www.telsell.com/themes/default/images/logo.png';
					imageElement.width = 48;
					imageElement.height = 41;
					Creative.Waad.Css.AddClassToElement(imageElement, 'tsp-img-item');
				}
				Creative.Waad.Css.AddClassToElement(divImageElement, 'tsp-img');
				aResultItemElement.appendChild(divImageElement);

				//Description element of result item
				divDescriptionElement = document.createElement('div');
				aResultItemElement.appendChild(divDescriptionElement);
				descriptionText = document.createTextNode(result[i].ProductTitle);
				Creative.Waad.Css.AddClassToElement(divDescriptionElement, 'tsp-description');
				divDescriptionElement.appendChild(descriptionText);

				//Category of result item
				divCategoryElement = document.createElement('div');
				divDescriptionElement.appendChild(divCategoryElement);
				if (result[i].CategoryDescription != null) {
					CategoryText = document.createTextNode(result[i].CategoryDescription);
					Creative.Waad.Css.AddClassToElement(divCategoryElement, 'tsp-category-description');
					divCategoryElement.appendChild(CategoryText);
				}

				//Div for Clear both
				divClear = document.createElement('div');
				Creative.Waad.Css.AddClassToElement(divClear, 'clear');
				aResultItemElement.appendChild(divClear);

			}
			if(i>0){
				resultHeaderText = 'Zoekresultaten (' + i + ' van ' + result.length + ')';
				divResultHeader.appendChild(document.createTextNode(resultHeaderText));
			}
		}
	},
	__resetElementNodes : function(element){
		if (element){
			while (element.hasChildNodes()){
				element.removeChild(element.firstChild );       
			}
		}
	},
	
	
	
	__currentInputChars : null,
	__resultObject : null,
	__searchButtonId : null,
	__textBoxId : null,
	__resultsPanelId : null,
	__currentCulture : null,
	__delay : null,
	__maxResults : null
}

TspScript.SetInitials = function(current_textbox_id, output_textbox_id) {
    var tResultValue = '';
    var tValue = $('#' + current_textbox_id).val();
    //Validate input
    var tPattern = /^[ a-zA-Z\áéíóäëiöúàèììù]*$/; //format pattern: only letters and spaces and special chars
    if (tPattern.test(tValue)) {
        // Add periods
        var tSplit = tValue.split(' ');
        for (var i = 0; i < tSplit.length; ++i) {
            if(tSplit[i].substr(0, 1)){
                tResultValue = tResultValue + tSplit[i].substr(0, 1).toUpperCase();
                if (tResultValue)
                    tResultValue = tResultValue + '.';
            }
        }
        $('#' + output_textbox_id).val(tResultValue);
    }

}
TspScript.FormatFirstname = function(current_textbox_id) {
    var tValue = $('#' + current_textbox_id).val();
    var tSplit = tValue.split(' ');
    tValue = '';
    for (var i = 0; i < tSplit.length; ++i) {
        // Just capitalize the first letter
        if (tSplit[i] && typeof (tSplit[i]) == 'string')
            tValue = tValue + tSplit[i].substr(0, 1).toUpperCase() + tSplit[i].substr(1).toLowerCase() + ' ';
    }
    tValue = TspScript.Trim(tValue);
    $('#' + current_textbox_id).val(tValue);
}
TspScript.Trim = function(value) {
    return value.replace(/(^\s+|(\s+$))/g, ''); //Removes spaces left and right of the input value
}
