﻿var oppManager = (function ($)
{
    var baseURI = window.location.protocol + "//" + window.location.host + "/DesktopModules/OpportunityManager/";

    var alerts =
	{
	    subscribe: function ()
	    {
	        var id = "#alerts-subscribe";

	        if (validate.form(id) == true)
	        {
	            captcha.check(function ()
	            {
	                $.ajax({
	                    url: baseURI + 'JSON.aspx?type=subscribe&command=signup&' + $(id + " input, " + id + " select").serialize(),
	                    dataType: 'jsonp',
	                    contentType: 'application/json',
	                    success: function (data)
	                    {
	                        if (data.key)
	                        {
	                            window.location = "/register/managesettings.aspx?key=" + data.key;
	                        }

	                        if (data.message)
	                        {
	                            var msg = $(id + " #message");

	                            msg.addClass(data.status).html(data.message).fadeIn(400).delay(6500).fadeOut(400);
	                        }
	                    },
	                    error: function (data)
	                    {
	                        alert("An error occurred");
	                    }
	                });
	            });

	        }
	        else
	        {
	            validate.show();
	        }

	    },

	    unsubscribe: function (key)
	    {
	        var id = "unsubscribe-dialog";
	        $("body").append("<div id=\"" + id + "\" style=\"display:none\"><p>If you wish to unsubscribe from a particular sector please click on 'Manage Alerts' otherwise click on 'Unsubscribe' to stop recieving all alerts.</p></div>");

	        $("#" + id).dialog(
			{
			    modal: true,
			    title: "Unsubscribe From Alerts",
			    resizable: false,
			    buttons:
				{
				    "Manage Alerts": function ()
				    {
				        $(this).dialog("close");
				    },
				    "Unsubscribe": function ()
				    {
				        $(this).dialog("close");
				        alerts.unSelectAll();
				        alerts.updateSettings(key);
				    }
				}
			});
	    },

	    updateSettings: function (key)
	    {
	        var msg = $("#subscriber-settings .message");
	        throbber.show();

	        $.ajax({
	            url: baseURI + 'JSON.aspx?type=subscribe&command=update&key=' + key + '&' + $("#subscriber-settings input").serialize(),
	            dataType: 'jsonp',
	            contentType: 'application/json',
	            success: function (data)
	            {
	                var c = $("#subscriber-settings input:checked").size(),
						m = "You're subscription settings have been successfully updated.";

	                if (c == 0)
	                {
	                    m += "<br/><br/>You are currently <strong>not subscribed to any sectors.</strong>";
	                }
	                else
	                {
	                    m += "<br/><br/>You are currently subscribed to <strong>" + c + " sectors.</strong>";
	                };

	                msg.removeClass("error").addClass("success").html(m);
	            },
	            error: function (data)
	            {
	                msg.addClass("error").removeClass("success").html("Sorry, an error has occurred and you're settings have not been updated.");
	            },
	            complete: function ()
	            {
	                throbber.hide();

	                msg.stop(true, true).show().delay(6000).fadeOut(300);

	                $('html, body').animate(
					{
					    scrollTop: (msg.offset().top - 40)
					}, 500);
	            }
	        });
	    },

	    selectAll: function ()
	    {
	        $("#subscriber-settings .sectors-list input[type=checkbox]").prop("checked", true);
	    },

	    unSelectAll: function ()
	    {
	        $("#subscriber-settings .sectors-list input[type=checkbox]").prop("checked", false);
	    }
	};


    var form =
	{
	    // enables any disabled fields in the specified form
	    // this allows disabled fields to be seralised 
	    unlock: function (id)
	    {
	        $(id + " [disabled]").attr("unlocked", "").prop("disabled", false);
	    },

	    // re-disables an fields that were previously unlocked
	    lock: function (id)
	    {
	        $(id + " [unlocked]").removeAttr("unlocked").prop("disabled", true);
	    }
	}

    var enquiry =
	{
	    // loads relevant data into form for current enquiry
	    loadData: function (editMode)
	    {
	        $("#OpID").val(opEnquiryData.ID);
	        enquiry.setTitle("Enquiry For: <span class=\"result-title\">" + opEnquiryData.Title + "</span>");

	        if (editMode)
	        {
	            $("#opportunity-title").html("Enquiry For: " + opEnquiryData.Title);

	            $.each(enquiryData, function (name, value)
	            {
	                var el = $("#" + name);

	                if (el.attr("type") === "checkbox")
	                {
	                    el.prop("checked", value);
	                }
	                else
	                {
	                    el.val(value);
	                }
	            });

	            if ($("#DeleteEnquiry") != null && $("#UpdateEnquiry") != null)
	            {
	                if (enquiryData.Deleted == null || enquiryData.Deleted == false)
	                {
	                    $("#DeleteEnquiry").attr('style', '');
	                    $("#UpdateEnquiry").attr('style', '');

	                    //	                    if ($("#RestoreEnquiry") != null)
	                    //	                    {
	                    //	                        $("#RestoreEnquiry").attr('style', 'display: none;');
	                    //	                    }
	                }
	                else
	                {
	                    $("#DeleteEnquiry").attr('style', 'display: none;');
	                    $("#UpdateEnquiry").attr('style', 'display: none;');

	                    //	                    if ($("#RestoreEnquiry") != null)
	                    //	                    {
	                    //	                        $("#RestoreEnquiry").attr('style', '');
	                    //	                    }
	                }
	            }
	        }
	    },

	    // make a few changes for the general enquiry type
	    initGen: function ()
	    {
	        $("#OpID").val("46"); // id=46 is a placeholder opportunity

	    },

	    setTitle: function (s)
	    {
	        $("#opportunity-title").html(s);
	    },

	    // submits the enquiry form to the server
	    submit: function ()
	    {
	        var id = '#opportunity-enquiry';

	        throbber.content = "Validating form, please wait";
	        throbber.show();

	        // check all required fields contain data
	        if (validate.form(id) == true)
	        {
	            // check captcha
	            captcha.check(function ()
	            {
	                throbber.content = "Sending enquiry, please wait";
	                throbber.show(); // forces the text to update

	                // save enquiry to database
	                $.ajax({
	                    url: baseURI + 'JSON.aspx?type=enquiry&command=save',
	                    dataType: 'jsonp',
	                    type: "POST",
	                    data: "{\"data\":" + JSON.stringify($(id + " input, " + id + " textarea, " + id + " select").serializeArray()) + "}",
	                    contentType: 'application/json',
	                    success: function (data)
	                    {
	                        if (data.message)
	                        {
	                            sessionStorage["opFormMessage"] = data.message;
	                        }

	                        if (data.ID !== 46)
	                        {
	                            window.location.href = "/opportunity/" + data.ID;
	                        }
	                        else
	                        {
	                            window.location.href = "/Opportunities.aspx";
	                        }
	                    },
	                    error: function (data)
	                    {
	                        alert("an error occurred");
	                    },
	                    complete: function ()
	                    {
	                        throbber.hide();
	                    }
	                });

	            });
	        }
	        else
	        {
	            validate.show();
	            throbber.hide();
	        }
	    },

	    // saves changes to an existing enquiry
	    update: function ()
	    {
	        var id = '#opportunity-enquiry';

	        throbber.content = "Validating form, please wait";
	        throbber.show();

	        // check all required fields contain data
	        if (validate.form(id) == true)
	        {
	            throbber.content = "Updating enquiry, please wait";

	            // save enquiry to database
	            $.ajax({
	                url: baseURI + 'JSON.aspx?type=enquiry&command=update',
	                dataType: 'jsonp',
	                type: "POST",
	                data: "{\"data\":" + JSON.stringify($(id + " input, " + id + " textarea, " + id + " select").serializeArray()) + "}",
	                contentType: 'application/json',
	                success: function (data)
	                {

	                    if (data.message)
	                    {
	                        sessionStorage["opFormMessage"] = data.message;
	                    }

	                    window.location.href = "/opportunities/manageenquiries.aspx";
	                },
	                error: function (data)
	                {
	                    alert("an error occurred");
	                },
	                complete: function ()
	                {
	                    throbber.hide();
	                }
	            });
	        }
	        else
	        {
	            validate.show();
	            throbber.hide();
	        }
	    },

	    // saves changes to an existing enquiry
	    setDeleted: function ()
	    {
	        var id = '#opportunity-enquiry';
	        throbber.content = "Validating form, please wait";
	        throbber.show();

	        // save enquiry to database
	        $.ajax({
	            url: baseURI + 'JSON.aspx?type=enquiry&command=delete',
	            dataType: 'jsonp',
	            type: "POST",
	            data: "{\"data\":" + JSON.stringify($(id + " input, " + id + " textarea, " + id + " select").serializeArray()) + "}",
	            contentType: 'application/json',
	            success: function (data)
	            {

	                if (data.message)
	                {
	                    sessionStorage["opFormMessage"] = data.message;
	                }

	                window.location.href = "/opportunities/manageenquiries.aspx";
	            },
	            error: function (data)
	            {
	                alert("an error occurred");
	            },
	            complete: function ()
	            {
	                throbber.hide();
	            }
	        });
	    },


	    // saves changes to an existing enquiry
	    restore: function ()
	    {
	        var id = '#opportunity-enquiry';
	        throbber.content = "Validating form, please wait";
	        throbber.show();

	        // save enquiry to database
	        $.ajax({
	            url: baseURI + 'JSON.aspx?type=enquiry&command=restore',
	            dataType: 'jsonp',
	            type: "POST",
	            data: "{\"data\":" + JSON.stringify($(id + " input, " + id + " textarea, " + id + " select").serializeArray()) + "}",
	            contentType: 'application/json',
	            success: function (data)
	            {

	                if (data.message)
	                {
	                    sessionStorage["opFormMessage"] = data.message;
	                }

	                window.location.href = "/opportunities/manageenquiries.aspx";
	            },
	            error: function (data)
	            {
	                alert("an error occurred");
	            },
	            complete: function ()
	            {
	                throbber.hide();
	            }
	        });
	    }
	};

    var edit =
	{
	    expireDate: function ()
	    {
	        var ex = $("#Expires");
	        var d = new Date();

	        if (ex.val() == "" || ex.val() == "/Date(-62135596800000+0000)/")
	        {
	            d.setFullYear(d.getFullYear() + 1);
	            ex.val(d.toUTCString());
	        }
	        else
	        {
	            d = new Date(parseInt(ex.val().replace(/\/Date\(/gi, "").replace(/\)\//gi, "")));
	            ex.val(d.toUTCString());
	        }

	        ex.val(ex.val().split("+0")[0]);

	        if ($.browser.msie)
	        {
	            ex.val(ex.val().replace(/UTC/, "GMT"));
	        }

	        ex.datepicker(
			{
			    dateFormat: "D, M d yy",
			    maxDate: "1Y",
			    minDate: "0Y",
			    changeMonth: true,
			    changeYear: true,
			    defaultDate: d
			});

	        ex.change(function ()
	        {
	            if (!/GMT/gi.test($(this).val()))
	            {
	                $(this).val($(this).val() + " 00:00:00 GMT");
	            };
	        });

	    },

	    setUni: function (u)
	    {
	        if (u !== "")
	        {
	            $("#University").val(u).prop("disabled", true);

	        }
	    },

	    loadData: function ()
	    {
	        if (opFormData)
	        {
	            $.each(opFormData, function (name, value)
	            {
	                if (name == "SectorsAdditional")
	                {
	                    // incase there is only one value...
	                    value += (/,/gi.test(value) ? "" : ",");

	                    // check appropriate checkboxes
	                    $.each(value.split(","), function (i, val)
	                    {
	                        $("#sa-" + val).prop("checked", true);
	                    });
	                }
	                else
	                {
	                    // form element
	                    var el = $("#" + name);

	                    // special case: checkbox
	                    if (el.attr("type") === "checkbox")
	                    {
	                        el.prop("checked", value);
	                    }
	                    // general fields
	                    else
	                    {
	                        el.val(value);
	                    };

	                    // display attached image
	                    if (name === "ImageURI")
	                    {
	                        $("#ImageContainer").html("<img src=\"" + value + "\" />");
	                    };

	                    // update page title to reflect current opportunity
	                    if (name === "Title")
	                    {
	                        $("#opportunity-title").html(value);
	                    };

	                    // check if element has a word count
	                    if (el.prop("hasWordLimit") == true)
	                    {
	                        el.keyup(); // will cause word count to update
	                    }
	                }
	            });

	        }
	        else
	        {
	            throw ("No form data was found.");
	        };
	    },


	    init: function ()
	    {
	        var id = "#opportunity-manager",
				del = $(id + " .button.delete"),
				res = $(id + " .button.restore");

	        if (typeof opFormData !== "undefined")
	        {
	            if (opFormData.Deleted == true)
	            {
	                del.hide();
	            }
	            else
	            {
	                res.hide();
	            };
	        }

	        // new opportunity
	        else
	        {
	            del.hide();
	            res.hide();
	        };

	        throbber.init();
	    },

	    del: function ()
	    {
	        throbber.content = "Deleting opportunity, please wait";
	        throbber.show();

	        $.ajax({
	            url: baseURI + 'JSON.aspx?type=opportunity&command=delete&ID=' + opFormData.ID,
	            type: "GET",
	            dataType: 'jsonp',
	            contentType: 'application/json',
	            success: function (data)
	            {
	                if (data.message)
	                {
	                    sessionStorage["opFormMessage"] = data.message;
	                }

	                window.location.href = "/Opportunities.aspx";
	            },
	            error: function (data)
	            {
	                if (data.message)
	                {
	                    alert(data.message);
	                }
	                else
	                {
	                    alert("an error occurred");
	                };
	            },
	            complete: function ()
	            {
	                throbber.hide()
	            }
	        });
	    },

	    restore: function ()
	    {
	        throbber.content = "Restoring opportunity, please wait";
	        throbber.show();

	        $.ajax({
	            url: baseURI + 'JSON.aspx?type=opportunity&command=restore&ID=' + opFormData.ID,
	            type: "GET",
	            dataType: 'jsonp',
	            contentType: 'application/json',
	            success: function (data)
	            {
	                if (data.message)
	                {
	                    sessionStorage["opFormMessage"] = data.message;
	                }

	                window.location.href = "/Opportunities.aspx";
	            },
	            error: function (data)
	            {
	                if (data.message)
	                {
	                    alert(data.message);
	                }
	                else
	                {
	                    alert("an error occurred");
	                };
	            },
	            compelte: function ()
	            {
	                throbber.hide();
	            }
	        });
	    },

	    submit: function ()
	    {
	        var id = "#opportunity-manager";
	        validate.reset();

	        throbber.content = "Validating form, please wait";
	        throbber.show();

	        // perform any appropriate validation on form fields
	        if (validate.form(id) == true)
	        {
	            form.unlock(id);
	            throbber.content = "Saving opportunity, please wait";
	            throbber.show(); // updates text immediately

	            $.ajax({
	                url: baseURI + 'JSON.aspx?type=opportunity&command=save&',
	                dataType: 'jsonp',
	                type: "POST",
	                data: "{\"data\":" + JSON.stringify($(id + " input, " + id + " textarea, " + id + " select").serializeArray()) + "}",
	                contentType: 'application/json',
	                success: function (data)
	                {
	                    if (data.message)
	                    {
	                        sessionStorage["opFormMessage"] = data.message;
	                    }

	                    window.location.href = "/opportunity/" + data.ID + "/" + data.Title.toLowerCase().replace(/( |%20)/gi, "-").replace(/[^a-z0-9-]/gi, '');
	                },
	                error: function (data)
	                {
	                    form.lock(id);

	                    if (data.message)
	                    {
	                        alert(data.message);
	                    }
	                    else
	                    {
	                        alert("an error occurred");
	                    };
	                },
	                complete: function ()
	                {
	                    throbber.hide();
	                }
	            });


	        }
	        else
	        {
	            validate.show();
	            throbber.hide();
	        }
	    },

	    editor:
		{
		    target: undefined,

		    init: function ()
		    {
		        $("#editor").dialog({
		            title: "Edit ...",
		            autoOpen: false,
		            modal: true,
		            width: 570
		        });

		        //$("#tiny-editor, #Description, #Abstract, #IPStatus").tinymce({
			$("#tiny-editor, #Abstract, #IPStatus").tinymce({
		            mode: "textareas",
		            theme: "advanced",
		            theme_advanced_buttons1: "bold,italic,underline,|,link,separator,bullist,numlist,|,undo,redo,|,sub,sup,|,charmap,cleanup,|,formatselect",
		            theme_advanced_buttons2: "",
		            theme_advanced_buttons3: ""
		        });

		        $("#editor .controls a").button();
		    },

		    // opens the rich text editor dialog
		    //	@id = id of the target text area
		    //	@limit = character limit to enforce
		    //	@title = (optional) override the dialog title
		    open: function (id, limit, title)
		    {
		        // update target for rich text editor
		        target = $(id);

		        // initialise editor
		        $("#tiny-editor").val(target.val());

		        // remove any old event bindings
		        oppManager.wordCount.remove('#editor');

		        // (re-)initalise word count
		        if (limit)
		        {
		            // update limit for current context
		            $('#editor .count').attr("limit", limit)
						.parent().show(); // make sure 'remaining' div is visible

		            // add event bindings
		            oppManager.wordCount.init('#editor');
		        }
		        else
		        {
		            $('#editor .remaining').hide();
		        }

		        // display to user
		        $('#editor').dialog("option", "title", "Edit " + (title ? title : id.replace("#", ""))).dialog('open');
		    },

		    close: function ()
		    {
		        // close editor dialog
		        $('#editor').dialog('close');

		        // disable target
		        target = undefined;
		    },

		    save: function ()
		    {
		        if (target)
		        {
		            // update target textarea with new code
		            target.val($("#tiny-editor").val());

		            // trigger keyup event on target textarea to enforce word limit
		            target.keyup();

		            // close editor dialog
		            this.close();
		        }
		    }
		},

	    // updates the page title when the title field is changed
	    title:
		{
		    init: function ()
		    {
		        $("#Title").keyup(function ()
		        {
		            $("#opportunity-title").html($(this).val());
		        });
		    }
		}
	};


    var list =
	{
	    opportunity: function ()
	    {
	        var grid = $("#opportunity-manager-list");

	        grid.jqGrid({
	            url: baseURI + 'Datagrid.aspx?type=opportunity',
	            datatype: "json",
	            height: '100%',
	            width: 930,
	            colNames: ['ID', 'Title', 'Created', 'Modified', 'Expires', 'University', 'Sector', 'Deleted', 'Published'],
	            colModel: [
					{ name: 'ID', index: 'ID', width: 40, sorttype: "int" },
					{ name: 'Title', index: 'Title', width: 240 },
					{ name: 'Created', index: 'Created', width: 50, sorttype: "date" },
					{ name: 'Modified', index: 'Modified', width: 50, sorttype: "date" },
					{ name: 'Expires', index: 'Expires', width: 50, sorttype: "date" },
					{ name: 'University', index: 'University', width: 90 },
					{ name: 'Sector', index: 'Sector', width: 90 },
					{ name: 'Deleted', index: 'Deleted', width: 45 },
					{ name: 'Published', index: 'Published', width: 45 }
				],
	            multiselect: false,
	            rowNum: 20,
	            rowList: [10, 20, 50, 100],
	            pager: '#opportunity-list-pager',
	            sortname: 'ID',
	            caption: "",
	            viewrecords: true,
	            sortorder: "desc",
	            sortable: true
	        });

	        grid.jqGrid('navGrid', '#opportunity-list-pager',
				{
				    edit: false,
				    add: false,
				    del: false
				},
				{}, {}, {}, // edit/add/delete options
				{
				sopt: ['cn', 'eq', 'ne'],
				top: grid.offset().top + 100,
				left: grid.offset().left + 250
}
			);

	        // add a click event listener to each cell
	        grid.find("td").live("click", function ()
	        {
	            var id = grid.jqGrid('getGridParam', 'selrow');

	            if (id)
	            {
	                var op = grid.jqGrid('getRowData', id);

	                window.location.href = "/opportunity/" + op.ID + "/" + op.Title.toLowerCase().replace(/( |%20)/gi, "-").replace(/[^a-z0-9-]/gi, '');
	            }
	        });
	    },


	    enquiry: function ()
	    {
	        //	        var grid = $("#opportunity-manager-enquiry-list");

	        //	        grid.jqGrid({
	        //	            url: baseURI + 'Datagrid.aspx?type=enquiry',
	        //	            datatype: "json",
	        //	            height: 461,
	        //	            width: 930,
	        //	            colNames: ['ID', 'Date', 'Status', 'Email', 'Name', 'Telephone', 'Country', 'Company', 'EnquiryText', 'Notes', 'Sector', 'University', 'Type'],
	        //	            colModel: [
	        //					{ name: 'ID', index: 'ID', width: 40, sorttype: "int" },
	        //					{ name: 'Date', index: 'Date', width: 80, sorttype: "date" },
	        //					{ name: 'Status', index: 'Status', width: 90 },
	        //					{ name: 'Email', index: 'Email', width: 90 },
	        //					{ name: 'Name', index: 'Name', width: 95 },
	        //					{ name: 'Telephone', index: 'Telephone', width: 95 },
	        //					{ name: 'Country', index: 'Country', width: 80 },
	        //					{ name: 'Company', index: 'Company', width: 90 },
	        //					{ name: 'EnquiryText', index: 'EnquiryText', width: 80 },
	        //					{ name: 'Notes', index: 'Notes', width: 50 },
	        //					{ name: 'Sector', index: 'Sector', width: 70 },
	        //					{ name: 'University', index: 'University', width: 90 },
	        //					{ name: 'Type', index: 'Type', width: 40 },
	        //				],
	        //	            multiselect: false,
	        //	            rowNum: 20,
	        //	            rowList: [10, 20, 50, 100],
	        //	            pager: '#enquiry-list-pager',
	        //	            sortname: 'ID',
	        //	            caption: "",
	        //	            viewrecords: true,
	        //	            sortorder: "desc",
	        //	            sortable: true
	        //	        });

	        //	        grid.jqGrid('navGrid', '#enquiry-list-pager',
	        //				{
	        //				    edit: false,
	        //				    add: false,
	        //				    del: false
	        //				},
	        //				{}, {}, {}, // edit/add/delete options
	        //				{
	        //				sopt: ['eq', 'ne', 'cn'],
	        //				top: grid.offset().top + 100,
	        //				left: grid.offset().left + 250
	        //                }
	        //			);


	        //	        // add a click event listener to each cell
	        //	        grid.find("td").live("click", function ()
	        //	        {
	        //	            var id = grid.jqGrid('getGridParam', 'selrow');

	        //	            if (id)
	        //	            {
	        //	                var en = grid.jqGrid('getRowData', id);

	        //	                window.location.href = "/opportunities/editenquiry.aspx?id=" + en.ID;
	        //	            }
	        //	        });


	        var specificGrid = $("#opportunity-manager-enquiry-specific-list");

	        specificGrid.jqGrid({
	            url: baseURI + 'Datagrid.aspx?type=enquirySpecific',
	            datatype: "json",
	            height: 461,
	            width: 930,
	            colNames: ['ID', 'Date', 'Status', 'Email', 'Name', 'Country', 'Company', 'Enq', 'Notes', 'Technology', 'University'],
	            colModel: [
					{ name: 'ID', index: 'ID', width: 40, sorttype: "int" },
					{ name: 'Date', index: 'Date', width: 80, sorttype: "date" },
					{ name: 'Status', index: 'Status', width: 90 },
					{ name: 'Email', index: 'Email', width: 70 },
					{ name: 'Name', index: 'Name', width: 95 },
	            //{ name: 'Telephone', index: 'Telephone', width: 95 },
					{name: 'Country', index: 'Country', width: 80 },
					{ name: 'Company', index: 'Company', width: 90 },
					{ name: 'EnquiryText', index: 'EnquiryText', width: 70 },
					{ name: 'Notes', index: 'Notes', width: 50 },
	            //{ name: 'Sector', index: 'Sector', width: 110 },
					{name: 'Technology', index: 'Technology', width: 235 },
					{ name: 'University', index: 'University', width: 90 },
	            //{ name: 'Type', index: 'Type', width: 40 },
				],
	            multiselect: false,
	            rowNum: 20,
	            rowList: [10, 20, 50, 100],
	            pager: '#enquiry-specific-list-pager',
	            sortname: 'ID',
	            caption: "",
	            viewrecords: true,
	            sortorder: "desc",
	            sortable: true
	        });

	        specificGrid.jqGrid('navGrid', '#enquiry-specific-list-pager',
				{
				    edit: false,
				    add: false,
				    del: false
				},
				{}, {}, {}, // edit/add/delete options
				{
				sopt: ['eq', 'ne', 'cn'],
				top: specificGrid.offset().top + 100,
				left: specificGrid.offset().left + 250
}
			);


	        // add a click event listener to each cell
	        specificGrid.find("td").live("click", function ()
	        {
	            var id = specificGrid.jqGrid('getGridParam', 'selrow');

	            if (id)
	            {
	                var en = specificGrid.jqGrid('getRowData', id);

	                window.location.href = "/opportunities/editenquiry.aspx?id=" + en.ID;
	            }
	        });


	        var generalGrid = $("#opportunity-manager-enquiry-general-list");

	        generalGrid.jqGrid({
	            url: baseURI + 'Datagrid.aspx?type=enquiryGeneral',
	            datatype: "json",
	            height: 461,
	            width: 930,
	            colNames: ['ID', 'Date', 'Status', 'Email', 'Name', 'Country', 'Company', 'EnquiryText', 'Notes', 'Technology', 'University'],
	            colModel: [
					{ name: 'ID', index: 'ID', width: 40, sorttype: "int" },
					{ name: 'Date', index: 'Date', width: 80, sorttype: "date" },
					{ name: 'Status', index: 'Status', width: 90 },
					{ name: 'Email', index: 'Email', width: 90 },
					{ name: 'Name', index: 'Name', width: 95 },
	            //{ name: 'Telephone', index: 'Telephone', width: 95 },
					{name: 'Country', index: 'Country', width: 80 },
					{ name: 'Company', index: 'Company', width: 90 },
					{ name: 'EnquiryText', index: 'EnquiryText', width: 175 },
					{ name: 'Notes', index: 'Notes', width: 50 },
	            //{ name: 'Sector', index: 'Sector', width: 110 },
					{ name: 'Technology', index: 'Technology', width: 110 },
					{ name: 'University', index: 'University', width: 90 },
	            //{ name: 'Type', index: 'Type', width: 40 },
				],
	            multiselect: false,
	            rowNum: 20,
	            rowList: [10, 20, 50, 100],
	            pager: '#enquiry-general-list-pager',
	            sortname: 'ID',
	            caption: "",
	            viewrecords: true,
	            sortorder: "desc",
	            sortable: true
	        });

	        generalGrid.jqGrid('navGrid', '#enquiry-general-list-pager',
				{
				    edit: false,
				    add: false,
				    del: false
				},
				{}, {}, {}, // edit/add/delete options
				{
				sopt: ['eq', 'ne', 'cn'],
				top: generalGrid.offset().top + 100,
				left: generalGrid.offset().left + 250
}
			);


	        // add a click event listener to each cell
	        generalGrid.find("td").live("click", function ()
	        {
	            var id = generalGrid.jqGrid('getGridParam', 'selrow');

	            if (id)
	            {
	                var en = generalGrid.jqGrid('getRowData', id);

	                window.location.href = "/opportunities/editenquiry.aspx?id=" + en.ID;
	            }
	        });
	    }
	};


    var tooltip =
	{
	    init: function (selector)
	    {
	        $(selector).find(".description").each(function ()
	        {
	            // try/catch required for IE6/7
	            try
	            {
	                var triggers = $(this).attr("for").split(" ");
	                var description = $(this);
	                description.appendTo("body");

	                $.each(triggers, function (i, trigger)
	                {
	                    // configure trigger element (hover)
	                    $("#" + trigger + ", label[for=" + trigger + "]").hover(
							function ()
							{
							    // reposition description
							    description.css(
								{
								    "top": ($("#" + trigger).offset().top) + "px",
								    "left": ($("#" + trigger).offset().left + $("#" + trigger).outerWidth()) + "px"
								});

							    // hide all descriptions - this stops multiple descriptions appearing if one has been activated by the focus event
							    $(".description").hide();

							    description.show();
							},
							function ()
							{
							    description.hide();
							}
						);


	                    // configure trigger element (focus)
	                    $("#" + trigger + ", label[for=" + trigger + "]").focus(
							function ()
							{
							    // reposition description
							    description.css(
								{
								    "top": ($("#" + trigger).offset().top) + "px",
								    "left": ($("#" + trigger).offset().left + $("#" + trigger).outerWidth()) + "px"
								});
							    description.show();
							});

	                    $("#" + trigger + ", label[for=" + trigger + "]").focusout(
							function ()
							{
							    description.hide();
							}
						);

	                });
	            }
	            catch (e) { };
	        });
	    }
	};


    var wordCount =
	{
	    init: function (selector)
	    {

	        setTimeout(function ()
	        {

	            $(selector).find(".count").each(function ()
	            {
	                var name = $(this).attr("for");
	                var trigger = $("#" + name);
	                var limit = 1 * $(this).attr("limit");
	                var count = $(this);
	                var useHtml = false; // should we use .html() instead of .val()


	                //console.log("#" + name + "_ifr" + "    " + $("#" + name + "_ifr").size());

	                // check to see if trigger is actually in an iframe (i.e. is a rich text editor)
	                if ($("#" + name + "_ifr").size() > 0)
	                {



	                    trigger = $("#" + name + "_ifr").contents().find("body");
	                    useHtml = true;


	                    setInterval(function ()
	                    {
	                        // get the number of remaining words
	                        words = limit - wordCount.total((useHtml ? trigger.html() : trigger.val()));

	                        // work out as percentage
	                        rPercent = words / limit * 100;
	                        rClass = "high";

	                        // set element class based on percentage
	                        if (rPercent < 66)
	                        {
	                            rClass = "medium";
	                        };
	                        if (rPercent < 33)
	                        {
	                            rClass = "low";
	                        };

	                        // update count element
	                        count.removeClass("low medium high").addClass(rClass).html(words);


	                    }, 1000);

	                    //console.log($("#" + name + "_ifr").contents().find("body").html());
	                };

	                // toggle active class
	                trigger.bind("focus", function ()
	                {
	                    count.addClass("active");
	                });
	                trigger.bind("focusout", function ()
	                {
	                    count.removeClass("active");
	                });


	                var words, rPercent, rClass;



	                trigger.bind("keydown", function (e)
	                {
	                    // get the number of remaining words
	                    words = limit - wordCount.total((useHtml ? $(this).html() : $(this).val()));

	                    // work out as percentage
	                    rPercent = words / limit * 100;
	                    rClass = "high";

	                    // set element class based on percentage
	                    if (rPercent < 66)
	                    {
	                        rClass = "medium";
	                    };
	                    if (rPercent < 33)
	                    {
	                        rClass = "low";
	                    };

	                    // update count element
	                    count.removeClass("low medium high").addClass(rClass).html(words);
	                });

	                trigger.bind("keyup", function (e)
	                {
	                    trigger.keydown();

	                    var val = (useHtml ? $(this).html() : $(this).val());

	                    // prevent more words from being typed into field
	                    if (words <= 0)
	                    {
	                        // remember current cursor position
	                        var start = trigger[0].selectionStart, end = trigger[0].selectionEnd;

	                        // remove any extra words/characters from input
	                        if (useHtml)
	                        {
	                            trigger.html(wordCount.reset(val, limit));
	                        }
	                        else
	                        {
	                            trigger.val(wordCount.reset(val, limit));
	                        };
	                        trigger.keydown();

	                        // reset cursor position
	                        if (trigger[0].setSelectionRange)
	                        {
	                            trigger[0].setSelectionRange(start, end);
	                        }
	                        else
	                        {
	                            trigger.click();
	                        }
	                    };
	                })

	                // mark element as having a word count enforced
	                trigger.prop("hasWordLimit", true);

	                // fire keyup event to set correct count on page init
	                trigger.keydown();

	            });


	        }, 1000);
	    },

	    // removes all event bindings for the specified counters
	    remove: function (selector)
	    {
	        $(selector).find(".count").each(function ()
	        {
	            var name = $(this).attr("for");
	            var trigger = $("#" + name);

	            // check to see if trigger is actually in an iframe (i.e. is a rich text editor)
	            if ($("#" + name + "_ifr").size() > 0)
	            {
	                trigger = $("#" + name + "_ifr").contents().find("body");
	            };

	            trigger.unbind();
	        });
	    },

	    // discards unwanted white space
	    clean: function (text)
	    {
	        // replace &nbsp; with a space
	        text = text.replace(/&nbsp;/gi, " ");

	        // reduce white space (matches 2 consecutive spaces)
	        text = text.replace(/\s+/gi, " ");

	        // remove any trailing spaces
	        while (text[text.length - 1] === " ")
	        {
	            text = text.slice(0, text.length - 1);
	        };

	        // remove any proceding spaces
	        while (text[0] === " ")
	        {
	            text = text.slice(1, text.length);
	        };

	        // remove extra newline/tab characters
	        text = text.replace(/\n\r\f\t\v/gi, "");

	        return text;
	    },

	    // strips unwanted html tags
	    strip: function (text)
	    {
	        return text.replace(/(<([^>]+)>)/ig, " ");
	    },

	    // return number of words in string
	    total: function (text)
	    {
	        return this.clean(this.strip(text)).split(" ").length + (text.length == 0 ? -1 : 0);
	    },

	    // return number of words (count html fragments as words) in a string
	    fragments: function (text)
	    {
	        return this.clean(text).split(" ").length + (text.length == 0 ? -1 : 0);
	    },

	    // enforces the word limit for a given string
	    reset: function (text, limit)
	    {
	        var toRemove = this.total(text) - limit;

	        if (toRemove > 0)
	        {
	            var parts = this.clean(text).split(" ").reverse();
	            var words = this.clean(this.strip(text)).split(" ").splice(limit, toRemove);

	            $.each(words, function (i, word)
	            {
	                var rword = new RegExp(RegExp.escape(word), "gi");

	                $.each(parts, function (i, part)
	                {
	                    // test if word is contained in this part/fragment
	                    if (rword.test(part))
	                    {
	                        parts[i] = part.replace(word, "");

	                        return false;
	                    };
	                });
	            });

	            text = parts.reverse().join(" ");
	        }

	        return text;
	    }

	};


    validate =
	{
	    message: null,

	    // scrolls page to show user validation messages
	    show: function ()
	    {
	        $('html, body').animate({
	            scrollTop: this.message.offset().top - 25
	        }, 1200);
	    },

	    // executes all validation tests for the specified form
	    form: function (id)
	    {
	        this.reset();

	        var t1 = this.required.check(id);
	        var t2 = this.email.check(id);
	        var t3 = this.video.check(id);
	        var t4 = this.html.check(id);

	        return t1 && t2 && t3;
	    },

	    // validates all email input fields on a form
	    email:
		{
		    test: function (email)
		    {
		        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		        return re.test(email);
		    },

		    check: function (selector)
		    {
		        var pass = true;

		        $(selector).find("[type=email]").each(function (i)
		        {
		            if ($(this).val() !== "")
		            {
		                if (validate.email.test($(this).val()) == false)
		                {
		                    pass = false;

		                    // mark field as failed
		                    $(this).parents(".field").addClass("error");

		                    // output a message to inform the user
		                    validate.message.addClass("error field").append("<div class=\"error\">Field <strong>'" + $("label[for=" + $(this).attr("id").replace("#", "") + "]").text().replace(":", "") + "'</strong> contains an <strong>invalid email address</strong>.</div>");
		                };
		            };
		        });

		        return pass;
		    }
		},

	    // validates all required fields
	    required:
		{
		    init: function (selector)
		    {
		        $(selector).find("[required]").each(function ()
		        {
		            $(this).before("<div class=\"required\" style=\"margin: 0 0 0 " + ($(this).outerWidth() + 3) + "px;\">*</div>");
		        });
		    },


		    check: function (selector)
		    {
		        var pass = true;

		        $(selector).find("[required]").each(function (i)
		        {

		            //console.log($(this).attr("id") + "   " + $(this).val() + "\n\n\n");

		            if ($(this).val() == "")
		            {
		                pass = false;

		                // mark field as failed
		                $(this).parents(".field").addClass("error");

		                // output a message to inform the user
		                validate.message.addClass("error field").append("<div class=\"error\">Field <strong>'" + $("label[for=" + $(this).attr("id").replace("#", "") + "]").text().replace(":", "") + "' is required</strong>.</div>");
		            }
		            else
		            {
		                $(this).parents(".field").removeClass("error");
		            }
		        });

		        return pass;
		    }

		},


	    // validates any text fields with an allowHTML attribute
	    html:
		{
		    test: function (fragment)
		    {
		        var re = /<(?:.|\s)*?>/g;
		        return re.test(fragment);
		    },

		    remove: function (fragment)
		    {
		        var re = /<(?:.|\s)*?>/g;
		        return fragment.replace(re, "");
		    },

		    check: function (selector)
		    {
		        var pass = true;

		        $(selector).find("textarea, input").not("[type=radio], [type=checkbox]").each(function (i)
		        {
		            var val = $(this).val();

		            if (val.length > 0)
		            {
		                // html is allowed
		                if ($(this).attr("allowhtml") === "true")
		                {
		                    // wrap value in paragraph tags if it currently contains no html tags
		                    if (!validate.html.test(val))
		                    {
		                        var _val = ("<p>" + val.replace(/\n/gi, "</p><p>").replace(/<p><\/p>/gi, "") + "</p>").replace(/<\/p>/gi, "</p>\n");
		                        $(this).val(_val);
		                    };
		                }
		                // html is restricted
		                else
		                {
		                    // if value contains any html tags remove them...
		                    if (validate.html.test(val))
		                    {
		                        $(this).val(validate.html.remove(val));
		                    };
		                }
		            };
		        });

		        return pass;
		    }
		},

	    // validates all emebed video code fields
	    video:
		{
		    test: function (code)
		    {
		        var xCode;

		        // try parsing code as xml
		        try
		        {
		            xCode = $($.parseXML(code));

		            // fix for webkit as it doesn't throw an error if the xml is parsed wrong
		            if (xCode.find("parsererror").size())
		            {
		                throw ("Invalid XML");
		            };
		        }
		        catch (e)
		        {
		            // try sanitising code then parse to xml
		            try
		            {
		                xCode = $($.parseXML(code.replace(/&/gi, "&amp;")));
		            }
		            catch (e)
		            {
		                // unable to parse so return as fail
		                return false;
		            };
		        }

		        // test our xml object - must be invalid if this fails
		        try
		        {
		            return ((xCode.find("object").size() + xCode.find("embed").size()) == 2 && xCode.find("param").size() > 0);
		        }
		        catch (e)
		        {
		            return false;
		        }
		    },

		    check: function (selector)
		    {
		        var pass = true;

		        $(selector).find("[type=video]").each(function (i)
		        {
		            if ($(this).val() !== "")
		            {
		                if (validate.video.test($(this).val()) == false)
		                {
		                    pass = false;

		                    // mark field as failed
		                    $(this).parents(".field").addClass("error");

		                    // output a message to inform the user
		                    validate.message.addClass("error field").append("<div class=\"error\">Field <strong>'" + $("label[for=" + $(this).attr("id").replace("#", "") + "]").text().replace(":", "") + "'</strong> contains <strong>invalid video embed code</strong>.</div>");
		                };
		            };
		        });

		        return pass;
		    }
		},

	    // clear old validation messages
	    reset: function ()
	    {
	        this.message = $("#message");
	        this.message.html("").removeClass("error");
	    }

	};


    var fileUpload =
	{
	    init: function ()
	    {
	        $("#ImageProgress").progressbar({ value: 0 }).hide();

	        new qq.FileUploader(
			{
			    element: $("#Image")[0],
			    action: baseURI + 'ImageUpload.aspx',
			    allowedExtensions: ["jpg", "jpeg", "png", "gif"],
			    onSubmit: function (id, file)
			    {
			        $("#ImageProgress")
						.stop(true, true).show()
						.progressbar("option", "value", 0)
						.find(".caption").html(file + ": <strong>0%</strong>");
			    },
			    onProgress: function (id, file, loaded, total)
			    {
			        var p = parseInt((loaded / total) * 100);

			        $("#ImageProgress")
						.progressbar("option", "value", p)
						.find(".caption").html(file + ": <strong>" + p + "%</strong>");
			    },
			    onComplete: function (id, file, response)
			    {
			        if (response.success == true)
			        {
			            $("#ImageContainer").html("<img src=\"" + response.location + response.filename + "\" />");

			            $("#ImageProgress")
							.progressbar("option", "value", 100)
							.delay(1000).fadeOut(500)
							.find(".caption").html(file + ": <strong>100%</strong>");

			            $("#ImageURI").val(response.location + response.filename);
			        };
			    }
			});

	        //$("#Image").before($("#Image .qq-uploader")).hide();
	        $(".qq-upload-button").addClass("button");
	    }


	};



    var captcha =
	{
	    init: function ()
	    {

	        $.ajax({
	            url: baseURI + 'JSON.aspx?type=captcha&command=getKey',
	            dataType: 'jsonp',
	            contentType: 'application/json',
	            success: function (data)
	            {
	                if (data.key)
	                {
	                    Recaptcha.create(
							data.key,
							"Recaptcha",
							{
							    theme: "clean",
							    callback: function ()
							    {
							        $("#recaptcha_response_field").attr("style", "width: 294px; border: 1px solid #ccc; border-radius: 3px; margin: 4px 2px 4px 0; padding: 5px 3px;");
							    }
							}
						);
	                }
	                else
	                {
	                    alert("Warning: Invalid captcha key returned!");
	                }
	            }
	        });


	    },

	    check: function (callback)
	    {
	        // check captcha is present
	        if (Recaptcha)
	        {
	            if (callback)
	            {
	                var c = Recaptcha.get_challenge(), r = Recaptcha.get_response();

	                var errorMsg = function ()
	                {
	                    // mark field as failed
	                    $("#Recaptcha").parents(".field").addClass("error");

	                    // output a message to inform the user
	                    validate.message.addClass("error field").append("<div class=\"error\">Field <strong>'Verification' is invalid</strong>.</div>");

	                    // close the throbber dialog if it's currently open
	                    throbber.hide();
	                };

	                if (c !== "" && r !== "")
	                {
	                    $.ajax({
	                        url: baseURI + 'JSON.aspx?type=captcha&challenge=' + c + '&response=' + r,
	                        dataType: 'jsonp',
	                        contentType: 'application/json',
	                        success: function (data)
	                        {
	                            if (data.valid == "True")
	                            {
	                                callback();
	                            }
	                            else
	                            {
	                                errorMsg();
	                            };
	                        },
	                        error: function (data)
	                        {
	                            errorMsg();
	                        }
	                    });
	                }
	                else
	                {
	                    errorMsg();
	                };
	            }
	            else
	            {
	                alert("a callback function is required");
	            };
	        }
	        else
	        {
	            alert("cannot submit without captcha");
	        };

	    }
	};



    var search =
	{
	    baseURI: "/opportunities/search/",

	    go: function ()
	    {

	        var id = "#opportunity-search",
	        //type = $(id + " #Type").val(), 
	        //order = $(id + " #Order").val().toLowerCase(),
	        //sort = $(id + " #Sort").val().toLowerCase(),
			university = $(id + " #University").val().toLowerCase(),
			keywords = $(id + " #Keywords").val(),
			sid = $(id + " #SID option[value=" + $(id + " #SID").val() + "]").text().replace(/ & /gi, "-and-").replace(/Please select\.\.\./gi, "").replace(/ /gi, "%20").replace(/,/gi, "%2c").toLowerCase();

	        //var q = (sid !== "" ? sid : "") + (university !== "" ? "/" + university : "/") + (keywords !== "" ? "/" + keywords : "");
	        var q = "";

	        if (sid != null && sid.toString().length > 0)
	        {
	            q = sid.toString();
	        }

	        if (university != null && university.toString().length > 0)
	        {
	            if (q.length == 0)
	            {
	                q = "-1/" + university.toString();
	            }
	            else
	            {
	                q = q + "/" + university.toString();
	            }
	        }
	        else
	        {
	            if ((q.length > 0) && (keywords != null && keywords.toString().length > 0))
	            {
	                q = q + "/-1";
	            }
	        }

	        if (keywords != null && keywords.toString().length > 0)
	        {
	            if (q.length == 0)
	            {
	                q = "-1/-1/" + keywords;
	            }
	            else
	            {
	                q = q + "/" + keywords;
	            }
	        }
	        else
	        {
	            if (university != null && university.toString().length > 0)
	            {
	                q = q + "/-1";
	            }
	        }

	        window.location.href = (this.baseURI + q.trimChar('/').replace("%20", "-")).trimChar('/') + "/0";
	    },

	    checkParams: function ()
	    {
	        if (typeof opSearchParams == "undefined" && typeof sessionStorage["opSearchParams"] !== "undefined")
	        {
	            var opSearchParams = $.parseJSON(sessionStorage["opSearchParams"])
	        }

	        if (typeof opSearchParams !== "undefined" && opSearchParams !== null)
	        {
	            if (opSearchParams.Sector != null && opSearchParams.Sector != "-1")
	            {
	                $('#opportunity-search #SID').val(opSearchParams.Sector);
	            }
	            $('#opportunity-search #Type').val(opSearchParams.Type);
	            //$('#opportunity-search #Order').val(opSearchParams.Order);
	            //$('#opportunity-search #Sort').val(opSearchParams.Sort);
	            if (opSearchParams.University != null && opSearchParams.University != "-1")
	            {
	                $('#opportunity-search #University').val(opSearchParams.University);
	            }
	            if (opSearchParams.Keywords != null && opSearchParams.Keywords != "-1")
	            {
	                $('#opportunity-search #Keywords').val(opSearchParams.Keywords);
	            }
	        }
	    },

	    reset: function ()
	    {
	        window.location.href = this.baseURI;
	    },

	    backLink: function ()
	    {
	        if (sessionStorage["lastSearch"])
	        {
	            // output "back to results" link
	            var link = $("#referrer-link");
	            if (link.size() == 0)
	            {
	                link.append("<a class=\"button\" href=\"" + sessionStorage["lastSearch"] + "\">Back To Results</a>");
	                link.find(".button").button();
	            }

	            // update breadcrumb
	            $("#breadcrumb a:contains('Opportunities')").after(" &gt; <a href=\"" + sessionStorage["lastSearch"] + "\">Search</a>");
	        };

	    },


	    init: function ()
	    {
	        var order = $("#Order");

	        // auto select order if 'sort by' is changed
	        $("#Sort").change(function ()
	        {
	            if ($(this).val() === "")
	            {
	                // reset order field
	                order.val("");
	            }
	            else
	            {
	                // only change if it has not already been selected
	                if (order.val() === "")
	                {
	                    if ($(this).val() === "title")
	                    {
	                        order.val("asc");
	                    }
	                    else
	                    {
	                        order.val("desc");
	                    }
	                };
	            }
	        });
	    }
	};


    var video =
	{
	    init: function (id, container, width)
	    {
	        $(id).change(function ()
	        {
	            if (validate.video.test($(this).val()))
	            {
	                $(container).html($(this).val());
	                video.rescale(container, (width ? width : 350));
	            };

	        });

	        $(id).change();

	    },

	    rescale: function (id, width)
	    {
	        $(id + ' object, ' + id + ' embed').each(function ()
	        {
	            var newWidth = (width ? width : 350),
					newHeight = (newWidth / $(this).width()) * $(this).height();

	            $(this).attr('width', newWidth);
	            $(this).attr('height', newHeight);
	        });

	    }
	};

    var query =
	{
	    param: function (name)
	    {
	        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	        var regexS = "[\\?&]" + name + "=([^&#]*)";
	        var regex = new RegExp(regexS);
	        var results = regex.exec(window.location.href);
	        if (results == null)
	        {
	            return "";
	        }
	        else
	        {
	            return decodeURIComponent(results[1].replace(/\+/g, " "));
	        };
	    }
	};

    // 'throbber' is used to show ajax requests are in progress
    var throbber =
	{
	    id: "throbber-dialog",
	    initialized: false,
	    interval: null,
	    content: "",

	    init: function (content)
	    {
	        if (!this.initialized)
	        {
	            // set default conent if no custom content is provided
	            if (!content)
	            {
	                this.content = "This may take a few moments, please wait.";
	            }
	            else
	            {
	                this.content = content;
	            };

	            // add dialog html to page
	            $("body").append("<div id=\"" + this.id + "\"><strong>" + this.content + "</strong></div>");
	            this.id = "#" + this.id;

	            // initialize dialog
	            $(this.id).dialog({
	                autoOpen: false,
	                modal: true,
	                minHeight: 1,
	                resizable: false
	            })
	            // hide the dialog title bar
				.parent().addClass("throbber").find(".ui-dialog-titlebar").hide();

	            this.initialized = true;
	        }
	    },

	    show: function ()
	    {
	        // make sure initial content displayed is correct (incase it has been changed since last shown)
	        $(this.id).html("<strong>" + this.content + "</strong>");

	        // open dialog
	        $(this.id).dialog("open");

	        // add some animated dots to dialog content
	        var dots = "";
	        this.interval = setInterval(function ()
	        {
	            $(throbber.id).html("<strong>" + throbber.content + dots + "</strong>");

	            dots += ".";
	            if (dots.length > 5)
	            {
	                dots = "";
	            };

	        }, 220);
	    },

	    hide: function ()
	    {
	        $(this.id).dialog("close");
	        clearInterval(this.interval);
	    }
	}


    var widget =
	{
	    code:
		{
		    refresh: function ()
		    {
		        var src = baseURI + "Widget.aspx?";

		        // add page size to query
		        src += "pageSize=" + $("#ops-widget-maker #ops-widget-pagesize").val();

		        // add sectors to query
		        $.each($("#ops-widget-maker .expandable input").serializeArray(), function (i, opt)
		        {
		            src += "&SID=" + opt.value;
		        });
		        //src = src.replace("?&", "?");

		        src += "&descLim=" + $("#ops-widget-maker #ops-widget-words-select").val();
		        src += "&styleSh=" + $("#ops-widget-maker #ops-widget-styles-select").val();
		        src += "&size=" + $("#ops-widget-maker #ops-widget-width-select").val();

		        $("#embed-code").val("<div id=\"ut-op-widget\"></div><script src=\"" + src + "\"></script>");
		    }
		},
	    opts:
		{
		    show: function ()
		    {
		        var button = $("#ops-widget-options");
		        button
					.attr("href", "javascript:oppManager.widget.opts.hide();")
					.find(".ui-button-text").html("Options &#708;");

		        var list = $("#ops-widget-maker .expandable");
		        list
					.stop(true, true).animate({ height: $(".expandable-inner").height() + 'px' }, 1000, 'swing')
					.css({ "padding": "10px", "border": "1px solid #eee" });

		    },
		    hide: function ()
		    {
		        var button = $("#ops-widget-options");
		        button
					.attr("href", "javascript:oppManager.widget.opts.show();")
					.find(".ui-button-text").html("Options &#709;");

		        var list = $("#ops-widget-maker .expandable");
		        list
					.stop(true, true).animate({ height: '0px' }, 700, 'swing', function ()
					{
					    $(this).css({ "padding": "0", "border": "0" });
					});
		    },
		    init: function ()
		    {
		        if (typeof opSearchParams !== "undefined")
		        {
		            if (opSearchParams.Sector !== "")
		            {
		                $("#ops-widget-maker #sec-" + opSearchParams.Sector).prop("checked", true);
		            }
		        };

		        $("#ops-widget-maker .expandable input").change(function ()
		        {
		            widget.code.refresh();
		        });


		        $("#embed-code")
				.focus(function ()
				{
				    this.select();
				})
				.click(function ()
				{
				    this.select();
				});



		        $("#ops-widget-pagesize-slider").slider(
				{
				    range: "min",
				    value: 5,
				    min: 1,
				    max: 25,
				    slide: function (event, ui)
				    {
				        $("#ops-widget-pagesize").val(ui.value);

				        widget.code.refresh();
				    }
				});

		        $("#ops-widget-pagesize").val($("#ops-widget-pagesize-slider").slider("value"));

		        $("#ops-widget-styles-select").change(function ()
		        {
		            widget.code.refresh();
		        });

		        $("#ops-widget-words-select").change(function ()
		        {
		            widget.code.refresh();
		        });

		        $("#ops-widget-width-select").change(function ()
		        {
		            widget.code.refresh();
		        });
		    }
		}
	};



    var forceList =
	{
	    newItem: function (base)
	    {
	        base.parent().find("input.forcelist-item:last").after("<input class=\"forcelist-item\" parent=\"" + base.attr("id") + "\" type=\"text\" placeholder=\"New item...\" />");
	    },

	    removeItem: function (base)
	    {
	        // remove first empty field
	        base.parent().find("input.forcelist-item").filter(function () { return this.value == ""; }).filter(":first").remove();

	        // set focus to remaining empty field
	        base.parent().find("input.forcelist-item").filter(function () { return this.value == ""; }).filter(":first").focus();
	    },

	    init: function (id)
	    {
	        $(id + " [forcelist]").each(function ()
	        {
	            var base = $(this);
	            base.hide();

	            var el = xcode.parse(base.val());

	            if (el != false && el.find("li").size() > 0)
	            {
	                el.find("li").each(function ()
	                {
	                    var input = "<input class=\"forcelist-item\" parent=\"" + base.attr("id") + "\" type=\"text\" value=\"" + $(this).text() + "\" />";

	                    if (base.parent().find("input.forcelist-item:last").size() == 0)
	                    {
	                        base.after(input);
	                    }
	                    else
	                    {
	                        base.parent().find("input.forcelist-item:last").after(input);
	                    }
	                });
	            }
	            else
	            {
	                base.after("<input class=\"forcelist-item\" parent=\"" + base.attr("id") + "\" type=\"text\" value=\"" + base.val() + "\"  />");
	            }

	            forceList.newItem(base);

	            $("input.forcelist-item").live("keyup", function ()
	            {
	                var isEmpty = false;

	                // get all list items for this group
	                var items = $("input.forcelist-item[parent=" + $(this).attr("parent") + "]");

	                // get base textarea
	                var base = $("#" + $(this).attr("parent"));

	                // check if a 'new item' field is required
	                if (items.filter(function () { return this.value == ""; }).size() == 0)
	                {
	                    forceList.newItem(base);
	                }
	                // check if there are any extra blank fields
	                else if (items.filter(function () { return this.value == ""; }).size() > 1)
	                {
	                    forceList.removeItem(base);
	                }
	                // check if we need to blank base field
	                else if (items.size() == 1 && items.filter(function () { return this.value == ""; }).size() == 1)
	                {
	                    isEmpty = true;
	                }


	                // build a new value to put in the base field
	                var value = "";
	                if (!isEmpty)
	                {
	                    value += "<ul>";
	                    items.each(function ()
	                    {
	                        if ($(this).val() !== "")
	                        {
	                            value += "<li>" + $(this).val() + "</li>";
	                        }
	                    });
	                    value += "</ul>";
	                }

	                base.val(value).keyup();

	            });
	        });
	    }


	}


    // transforms xml code into a jQuery object
    var xcode =
	{
	    parse: function (code)
	    {
	        var _xCode;

	        // try parsing code as xml
	        try
	        {
	            _xCode = $($.parseXML(code));

	            // fix for webkit as it doesn't throw an error if the xml is parsed wrong
	            if (_xCode.find("parsererror").size())
	            {
	                //console.log("Invalid XML");

	                throw ("Invalid XML");
	            };
	        }
	        catch (e)
	        {
	            // try sanitising code then parse to xml
	            try
	            {
	                _xCode = $($.parseXML(code.replace(/&/gi, "&amp;")));
	            }
	            catch (e)
	            {
	                // unable to parse so return as fail
	                return false;
	            };
	        }

	        return _xCode;
	    }
	}


    return {
        baseURI: baseURI,
        list: list,
        edit: edit,
        enquiry: enquiry,
        fileUpload: fileUpload,
        required: validate.required,
        tooltip: tooltip,
        wordCount: wordCount,
        captcha: captcha,
        search: search,
        video: video,
        form: form,
        alerts: alerts,
        throbber: throbber,
        widget: widget,
        forceList: forceList
    }

})(jQuery);


// transform 'button' links into jquery buttons
$(document).ready(function()
{
	// bind hover event to elements that look like buttons but are not proper jquery ones
	$("[role=button]").hover(function()
	{
		$(this).addClass("ui-state-hover");
	},
	function()
	{
		$(this).removeClass("ui-state-hover");
	});

	// transform non-buttons into buttons
	$(".button").not("[role=button]").button();
});


// make's sure strings are safe to convert to a regex
RegExp.escape = function(text) 
{
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

// capitalize a string
String.prototype.capitalize = function()
{
	return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};

// removes the specified character from the end of a string
String.prototype.trimChar = function(c)
{
	var s = this;
	while (s.length > 0 && s[s.length-1] == c)
	{
		s = s.substring(0, s.length - 1);
	}
	return s;
}


function ToggleCheckBoxes(button)
{
    var checked = true;

    if ($("#" + button) != null)
    {
        if ($("#" + button).attr("value").toString().indexOf("Select All") == 0)
        {
            $("#" + button).attr("value", "Reset All CheckBoxes");
        }
        else
        {
            checked = false;
            $("#" + button).attr("value", "Select All CheckBoxes");
        }
    }

    $(".CheckBox").each(function ()
    {
        $(this).attr("checked", checked);
    });

    oppManager.widget.code.refresh();
}




var pIdx = 0;        // print frame index

function ShowPrintWindow(printableFormType)
{
    pIdx++;

    if ($.browser.msie)
    {
        var tmp = window.open("/DesktopModules/OpportunityManager/IFRAME.aspx?pft=" + printableFormType, 
                              "printform" + pIdx,
                              "status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,height=500")

        setTimeout(function ()
                   {
                        tmp.close();
                   },
                   5000);
    }
    else
    {
        $("body").append("<iframe id=\"print-frame-" + pIdx +
                         "\" style=\"width:0;height:0\" src=\"/DesktopModules/OpportunityManager/IFRAME.aspx?pft=" + 
                         printableFormType + "\"></iframe>");

        setTimeout(function ()
                   {
                        $("#print-frame-" + pIdx).remove();
                   },
                   5000);
    }
};

