/// <reference path="./js/com/jquery/jquery-1.3.2-vsdoc.js" />


//
// Base namespace declaration
var PogoJo = {};


//
// Global code initialisation
$(function() {

	//
	// Namespace initialisation calls
	// PogoJo.TextCounter.Initialise();
	PogoJo.Effects.Initialise();
	PogoJo.Menubar.Initialise();
    PogoJo.FormFields.ToolTips.Initialise();
});


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.TextCounter
PogoJo.TextCounter = (function() {

	//
	// This is the general purpose changed event handler
	// for both INPUT and TEXTAREA elements. It is assumed
	// that the TEXTAREA elements will have a manually added
	// attribute for MaxLength (this is done on init)
	var changed = function(maxLength) {
	
		// Get the max length and the ui display field
		var maxLength = $(this).attr('maxLength');
		var span = $('span.countTextSpan', $(this).parent());
		
		// Make sure there is a field to update
		if (span === undefined)
			return;
			
		// Make sure the maxlength is valid
		if (maxLength === undefined || maxLength === null) {
			span.html('[maxlength not defined]');
			return;
		}

		// Update the UI SPAN element		
		$(this).parent()
			   .find("span.countTextSpan")
			   .html($(this).val().length + ' of ' + maxLength + ' characters used');
	};

    return {
    
		//
		// Initialises the text counters on the page
        Initialise: function () {
			
			var areas = $('textarea.countText');
			var textboxes = $('input[type=text].countText');
			var spanHtml = '<span class="countTextSpan"></span>';
			
			// Setup all the INPUT elements on the form
			textboxes.keyup(changed);
			textboxes.after(spanHtml);
			textboxes.each(changed);
			
			// Setup all the TEXTAREA elements on the form
			// The length is given through the class definition
			// by specifying an extra class: len(x), where x
			// is the maxlength value.
			// The init code will parse this and store it in 
			// a manually added attribute.			
			areas.after(spanHtml);
			areas.each(function() {
			
				// Get the maxlength definition start
				var si = this.className.indexOf("len(");
				
				if (si == -1) {
					return;
				}
				
				si += 4;
				
				// Get the maxlength definition end
				var ei = this.className.indexOf(")");
				
				if (ei == -1) {
					return;
				}
				
				// Parse the maxlength
				var len = parseInt(this.className.substring(si, ei), 10);
				
				// Assign the element properties
				$(this).attr('maxLength', len)
				$(this)[0].onkeyup = changed;
				
				// Init the element by calling the event handler manually
				changed.call(this, len);
			});
        }
    };

})();

PogoJo.FormFields = {};

//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields
PogoJo.FormFields = (function() {

	return {
		//
		// Common functionality to parse a JSON response and
		// populate a given dropdown (select) control.
		ParseData: function(target, data) {
			// Blast the lists contents
			target.html("");

			// Create the list items
			if (data !== undefined) {
				for (i = 0; i < data.length; i++) {
					target.get(0).add(new Option(data[i].text, data[i].id), document.all ? i : null);
				}
			}

			//select first option
			$("option:first", target).attr("selected", "selected");
		},		
		
		//
		// 
		SetEnabled: function(drop, condition) {
			if (condition) {
				drop.attr("disabled", "true");
			}
			else {
				drop.removeAttr("disabled");
			}
		}
	};
})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.Rating
PogoJo.FormFields.Rating = (function() {

	var editorRating = function(jelem) {
		return parseInt(jelem.attr("id").substring(6));
	};
	
	var getRatingImg = function(index) {
		return $("img#rating" + index);
	};
	
	//
	// Sets the current rating display based on the 
	// given index
	var setRating = function(idx) {
		for (var i = 1; i <= idx ; i++) {
		    getRatingImg(i).attr("src", "../images1/icon_rating.jpg");
		}
		
		for (var i = idx + 1; i <= 5 ; i++) {
		    getRatingImg(i).attr("src", "../images/icon_rating_off.jpg");
		}
	};

	return {
	
		//
		// Initialise function to setup the functionality of this namespace
		Initialise: function(hiddenSelector) {
	
			// Handler to reset the rating display to whatever is in 
			// the asp.net hidden form field on mouse leave
			$("div.documentCommenter_O div.formInput_O").bind("mouseleave", function() {
			
				var idx = parseInt(hiddenSelector.val(), 10);
			
				setRating(idx);
			});
		
			// Handler to show a preview of where the rating will be set
			// if the user chooses to click (the above mouseleave handler
			// will reset the rating if they move away).
			$("img.rating").hover(function() {
			
				var idx = editorRating($(this));
			
				setRating(idx);
			});	
			
			// Handler to update the hidden asp.net value field 
			// with the index of the clicked rating icon
			$("img.rating").click(function() {
			
				var idx = editorRating($(this));
			
				hiddenSelector.val(idx)
			});
		}
	};
})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.StateAndUniversity
PogoJo.FormFields.StateAndUniversity = (function () {

    var stateDrop;
    var uniDrop;
    var hiddenValue;

    //
    // Called to start the ajax request to the server
    var updateUniversities = function () {
        // Create the request parameters object
        var parameters = { search: stateDrop.val() };

        $.getJSON("/api/getuniversities.ashx", parameters, callback);
    };

    //
    // Processes the result universities and populates the dropdown
    var callback = function (data, textStatus) {

        // Populate the dropdown
        PogoJo.FormFields.ParseData(uniDrop, data);
        PogoJo.FormFields.SetEnabled(uniDrop, data.length == 0);

        uniDrop.get(0).add(new Option("Other...", 0), document.all ? i : null);

        if (onUniChanged !== undefined) {
            onUniChanged();
        }

        updateHidden();
    };

    //
    //
    var updateHidden = function () {
        hiddenValue.val(uniDrop.val());
    };

    return {

        //
        // 
        Initialise: function (stateTarget, uniTarget, hiddenTarget) {

            stateDrop = stateTarget;
            stateDrop.change(updateUniversities);

            uniDrop = uniTarget;
            uniDrop.change(updateHidden);

            hiddenValue = hiddenTarget;

            if (onUniChanged !== undefined) {
                uniDrop.change(onUniChanged);
            }
        }
    };
})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.FieldsOfStudyQuickSearch
PogoJo.FormFields.FieldsOfStudyQuickSearch = (function() {

	var callback = function(data) {
	    
		var areasOfStudy = $("div#areasOfStudy");
		var html = "";
		
		html += "<div class='content'>";
      	html += "<div class='list'>";
		html += "<ul>";
		
		var totalDocs = 0;
		
		for (var i = 0; i < data.length; i++) {
			totalDocs += parseInt(data[i].count);
		}
		
		var fieldId = $("div#fieldsOfStudy ul li a.selected").attr("rel");
		
		html += "<li><a href='/public/search.aspx?field=" + fieldId + "'>All<strong>(" + totalDocs + ")</strong></a></li>";
		
		for (var i = 0; i < data.length; i++) {
			var areaId = data[i].id;
			var areaText = data[i].text;
			var areaCount = data[i].count;

			html += "<li><a href='/public/search.aspx?field=" + fieldId + "&area=" + areaId + "'>";
			html += areaText + "<strong>(" +  areaCount + ")</strong>";
			html += "</a></li>";
		}
		
		html += "</ul>";
		html += "</div>";
		html += "</div>";
		
		areasOfStudy.html(html);
	};

	return {
	
		Initialise: function() {
		
			$("div#fieldsOfStudy ul li:eq(0) a").addClass("selected");
		
			$("div#fieldsOfStudy a").click(function(e) {
			
				var link = $(e.currentTarget);
				var fieldId = link.attr("rel");
		        var parameters = { search: fieldId };

				$.getJSON("/api/getfields.ashx", parameters, callback);
				
				$("div#fieldsOfStudy a").removeClass("selected");
				link.addClass("selected");
				
				return false;
			});
		}
	}

})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.FieldOfStudyAndAreaOfStudy
PogoJo.FormFields.FieldOfStudyAndAreaOfStudy = (function() {

	var areaDrop;
	var fieldDrop;
	var hiddenValue;
    
	//
    // Called to start the ajax request to the server
    var updateFields = function() {
        // Create the request parameters object
        var parameters = { search: areaDrop.val() };

        $.getJSON("/api/getfields.ashx", parameters, callback);
    };

	//
    // Processes the result study areas and populates the study areas
    // dropdown.
    var callback = function(data, textStatus) {
        PogoJo.FormFields.ParseData(fieldDrop, data);
        PogoJo.FormFields.SetEnabled(fieldDrop, data.length == 0);
        
        updateHidden();
    };
    
    //
    //
    var updateHidden = function() {
		hiddenValue.val(fieldDrop.val());
    };

	return {
	
		//
		// Setup for the namespace
		Initialise: function(areaTarget, fieldTarget, hiddenTarget) {
		
			areaDrop = areaTarget;
			areaDrop.change(updateFields);
			
			fieldDrop = fieldTarget;
			fieldDrop.change(updateHidden);
			
			hiddenValue = hiddenTarget;
		}
	};
})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.PaperAndSubs
PogoJo.FormFields.PaperAndSubs = (function() {

	var paperDrop;
	var subDrop;
	var hiddenValue;

	//
    // Processes the result and populates the dropdown.
    var callback = function(data, textStatus) {
    	PogoJo.FormFields.ParseData(subDrop, data);
        PogoJo.FormFields.SetEnabled(subDrop, data.length == 0);
        
        updateHidden();
    };
    
    //
    //
    var updateHidden = function() {
		hiddenValue.val(subDrop.val());
    };
    
	//
    // Called to start the ajax request to the server
    var updateFields = function() {
        // Create the request parameters object
        var parameters = { search: paperDrop.val() };

        $.getJSON("/api/getpapersubs.ashx", parameters, callback);
    };

	return {
	
		//
		// Setup for the namespace
		Initialise: function(paperTarget, subTarget, hiddenTarget) {
		
			paperDrop = paperTarget;
			paperDrop.change(updateFields);
			
			subDrop = subTarget;
			subDrop.change(updateHidden);
			
			hiddenValue = hiddenTarget;
		}
	};
})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.ToolTips
PogoJo.FormFields.ToolTips = (function() {

	return {
	
		//
		// Setup for the namespace
		Initialise: function() {
			// Start tooltips running on all help form elements
			var params = ({ extraClass: "tooltip", track: true, delay: 0, showURL: false, showBody: " - "});

			$("div.help").tooltip(params);
		}
	}

})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.MasterPage
PogoJo.FormFields.MasterPage = (function () {

    //------
    // Performs a redirect to the search page and constructs the 
    // query string parameters to pass the search criteria across.
    var doSearchRedirect = function () {
               
        var term = $("div.searchPane_O input#term").val();
        var fieldsOfStudy = $("div.searchPane_O select#fieldsOfStudyDrop").val();
        var paperType = $("div.searchPane_O select#paperTypeDrop").val();
        var queryObject = $.jqURL.qs({ ret: 'object' });


        queryObject["term"] = term;

        if (fieldsOfStudy != "All") {
            queryObject["field"] = fieldsOfStudy;
            queryObject["area"] = fieldsOfStudy;
        }
        else {
            delete queryObject["field"];
            delete queryObject["area"];
        }

        if (paperType != "All") {
            queryObject["paper"] = paperType;
        }

        // Builder the query string
        var url = PogoJo.Utilities.BuildUrl("/public/search.aspx", queryObject);

        window.location = url;
    };

    return {

        //-----
        // 
        Initialise: function () {
            var searchBtn = $("div.searchPane_O a#searchBtn");
            var termInput = $("div.searchPane_O input#term");
            var fieldsOfStudyDrop = $("div.searchPane_O select#fieldsOfStudyDrop");
            var paperTypeDrop = $("div.searchPane_O select#paperTypeDrop");

            var termText = $.jqURL.get("term");

            if (termText !== undefined) {

                var re = new RegExp('%20', "g")
                termText = termText.replace(re, " ");
                termText = termText.replace('#', " ");
                termText = unescape(termText);


            }

            if (termText !== undefined)
                termText = termText.replace(/%20/gi, " ");


            var currentTerm = termText;
            var currentField = $.jqURL.get("field");
            var currentPaperType = $.jqURL.get("paper");

            termInput.val(currentTerm);
            fieldsOfStudyDrop.val(currentField);
            paperTypeDrop.val(currentPaperType);

            $("div.searchPane_O a#searchBtn").click(doSearchRedirect);

            // Listen for 'enter' keypress on the search term to kick off a new search
            termInput.keydown(function (e) {
                if (e.keyCode == 13) {
                    doSearchRedirect();
                }
            });

            termInput.focus();
        }
    }

})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.FormFields.SearchQuickFilter
PogoJo.FormFields.SearchQuickFilter = (function() {

	var updateSearch = function(list, queryName, e) {
	
		var anchor = $(e.currentTarget);
		var queryObject = $.jqURL.qs({ ret:'object' });
		var value = anchor.attr("rel");
		
		// Add the value to the query object
		if (value !== undefined && value.length > 0) {
			queryObject[queryName] = value;
			if(queryName == "area")
			{
			    queryObject["field"]=value;
			}
			else if(queryName == "field")
			{
			    queryObject["area"]=value;
			}
		}
		else if (queryObject[queryName] !== undefined) {
			// Otherwise the 'all' entry must have been selected
			// and we want to remove the element from the query
			// string
			delete queryObject[queryName];
			if(queryName == "area")
			{
			    delete queryObject["field"];
			}
		}
		
		// Add the search term too!
		var term = $("div.searchTerm input#term").val();
		
		if (term !== undefined && term.length > 0) {
			queryObject["term"] = term;
		}
		
		// Builder the url
		var url = PogoJo.Utilities.BuildUrl("/public/search.aspx", queryObject);
		
		// Redirect
		window.location = url;

		return false;
	};
	
	//------
	// 
	var initList = function(list, rel, queryName) {
	
		if (rel !== undefined) {
			
			var anchor = $("div#" + list + " a[rel=" + rel + "]");
			
			anchor.addClass("selected");
			
			if (anchor.length > 0) {
				anchor[0].scrollIntoView(true);
			}
		}
		
		if ($("div#" + list + " a.selected").length == 0) {
			$("div#" + list + " a:eq(0)").addClass("selected");
		}
			
		$("div#" + list + " a").click(function(e) { return updateSearch(list, queryName, e); });
	}

	return {
		
		Initialise: function() {
		
			var fieldOfStudy = unescape($.jqURL.get("field"));
			var areaOfStudy = unescape($.jqURL.get("area"));
			var paperType = $.jqURL.get("paper");
			var studyLevel = $.jqURL.get("study");
			var university = $.jqURL.get("in");
			var year = $.jqURL.get("year");
			
			// Do we need to select the first column based on area or field?
			// Remember the list is interchangable! If there is a field in
			// active filter then we have areas listed and need to select one
			// of those, otherwise make sure the first 'all' entry is selected.
			if (fieldOfStudy !== undefined || areaOfStudy !== undefined) {
				initList("fields", areaOfStudy, "area");
			}
			else {
				initList("fields", fieldOfStudy, "field");
			}
			
			initList("paperTypes", paperType, "paper");
			initList("studyLevels", studyLevel, "study");
			initList("universityList", university, "in");
			initList("yearsList", year, "year");
		}
	};
})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.Utilities
PogoJo.Utilities = (function() {

	return {

		BuildUrl: function(url, queryArray) {
			var query = PogoJo.Utilities.ArrayToQueryString(queryArray);
			if (query.length == 0)
				return url;
				
			return url + "?" + query;
		},

		//------
		// Converts an asssociative array to a query string		
		ArrayToQueryString: function(array) {
			// Builder the query string
			var queryString = "";
			
			for (var key in array) {
			
				if (key === undefined || key == null || key.length == 0) {
					continue;
				}
				
				var value = array[key];
				
				if (value === undefined || value == null || value.length == 0) {
					continue;
				}
			
				if (queryString.length > 0) {
					queryString += "&";
				}
			
				queryString += key;
				queryString += "=";
				queryString += value;
			}
			
			return queryString;
		}
	}
})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.Ambassador
PogoJo.Ambassador = (function() {

	//
    // 
    var getAmbassadorCallback = function(data, textStatus) {
        setAmbassadorId(data.ambassadorId);
    };
    
    //
    //
    var setAmbassadorId = function(id) {
        $('#<%= AmbassadorId.ClientID %>').innerText = id;
        $('#<%= AmbassadorIdHidden.ClientID %>').innerText = id;
    };

	return {
	
		//
		// Initialises the ambassador functionality
		Initialise: function() {
			$('#<%= IsAmbassadorCheck.ClientID %>').click(function() {
				var userId = $('#<%= UserIdHidden.ClientID %>');
				var params = { userId: userId.val() };
	        
				// Attempt to set the ambassador id only if the box is checked
				if ($('#<%= IsAmbassadorCheck.ClientID %>').val()) {
					// If this user already has an ambassador id then prevent a postback to the server
					if ($('#<%= AmbassadorIdHidden.ClientID %>').innerText.length > 0)
					{
						setAmbassadorId($('#<%= AmbassadorIdHidden.ClientID %>').innerText);
					}
					else{
						$.getJSON("/api/getambassadorid/", params, getAmbassadorCallback);
					}
				}
			});
		}
	}

})();


//------------------------------------------------------------------------------
//
// Namespace: PogoJo.Effects
PogoJo.Effects = (function() {
	
	return {
	
		//
		// Namespace initialisation function
		Initialise: function() {
			$('div.demo-show2> div').hide();
			$('div.demo-show2> h2').click(function() {
				var $nextDiv = $(this).next();
				var $visibleSiblings = $nextDiv.siblings('div:visible');

				if ($visibleSiblings.length) {
					$visibleSiblings.slideUp('fast', function() {
						$nextDiv.slideToggle('fast');
					});
				} else {
					$nextDiv.slideToggle('fast');
				}
			});
		}
	};

})();


//
// Namespace: PogoJo.Menubar
PogoJo.Menubar = (function() {
	
	var timeout = 500;
	var closetimer = 0;
	var ddmenuitem = 0;
	
	var open = function() {
		canceltimer();
		close();
		ddmenuitem = $(this).find('ul').css('visibility', 'visible');
	};

	var close = function() { 
		if (ddmenuitem) 
			ddmenuitem.css('visibility', 'hidden'); 
	};

	var timer = function() { 
		closetimer = window.setTimeout(close, timeout); 
	};

	var canceltimer = function() {
		if (closetimer) {
			window.clearTimeout(closetimer);
			closetimer = null;
		}
	};
	
	return {
	
		//
		// Menubar initialisation function
		Initialise: function() {
		
			$('#nav > li').hover(open, timer);

			document.onclick = close;
		}
	};
	
})();







