﻿/// <reference path="jquery-1.5.min.js" />

function InitFormWizard(validationOption, step2) {
	$("#stepwizardform").formwizard({
		historyEnabled: true,
		focusFirstInput: true,
		disableUIStyles: true,
		next: 'input.form_next',
		back: 'input.form_back',
		inDuration: 0,
		outDuration: 0,
		textNext: '',
		textBack: '',
		textSubmit: '',
		disableInputFields: true,
		validationEnabled: true,
		validationOptions: validationOption,
		restoreDisabledInputFields: true
	});

	$("#stepwizardform").bind("step_shown", function (event, data) {
		var next = $('input.form_next');
		var back = $('input.form_back');
		if (data.isLastStep) {
			next.toggleClass('form_submit')
		}
		else {
			next.removeClass('form_submit')
		}

		if (data.isFirstStep) {
			back.hide();
		}
		else {
			back.show();
		}

		var index = data.currentStep.charAt(data.currentStep.length - 1) - 1;

		var liList = $("div.uiStepList li");
		var currLi = $("div.uiStepList li").eq(index);

		liList.removeClass("uiStepNextSelected uiStepSelected");

		if (index > 0) {
			liList.eq(index - 1).toggleClass("uiStepNextSelected");
		}

		currLi.toggleClass("uiStepSelected");

		if (step2 != null)
		{
			step2();
		}
	});

//    $("div.uiStepList li").click(function () {
//        var currLi = $(this);

//        if (currLi.hasClass("uiStepSelected") == false) {
//            var liList = $("div.uiStepList li");
//            var index = liList.index(this);
//            $("#stepwizardform").formwizard("show", "step" + (index + 1));
//        }
//        //var currStep = $("div#step" + index);
//    });

	var currUrl = document.location.hash;
	if (currUrl != "") { // the URL contains an anchor
		//check if url hash have _stepwizardform
		var index = currUrl.indexOf("_stepwizardform");
		if (index != -1) {
			var stepID = currUrl.substr(index + 16, currUrl.length - index + 16);
			window.location.href = window.location.href.replace(stepID, "step1");
			$("#stepwizardform").formwizard("show", stepID);
		}
	}
	removeErrorOnBlur();
}

function InitLearnerProfile() {
	$("#selectedcategories").fcbkcomplete({
		json_url: '/categories/search',
		addontab: true,
		height: 5,
		complete_text: 'Type to start..',
		maxshownitems: 10,
		maxitems: 500,
		onselect: aoi_select,
		onremove: aoi_remove
	});

	var catList = $('div.aoi_list_cat');

	$('body').append(catList);
	catList = null;

	$("#aoi_select").click(
		function () {
			var scDialog = $('div.aoi_modal_catlist');

			//create share dialog
			scDialog.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: false,
				width: '875px',
				height: '500',
				title: 'Areas of Interest',
				open: function (event, ui) {
					var catList = $('div.aoi_list_cat');
					scDialog.append(catList);
					catList.show();
					if ($.browser.msie) {
						var selectedCats = $("select#selectedcategories option:selected");
						$("div.aoi_list_cat input[type='checkbox']").attr('checked', false);
						selectedCats.each(function (index) {
							var chk = "cat" + $(this).val();
							$("#" + chk).attr('checked', true);
						});
					}
					catList = null;
				},
				beforeClose: function (event, ui) {
					var catList = $('div.aoi_list_cat');
					catList.hide();
					$('body').append(catList);
					catList = null;
					scDialog.empty();

					scDialog.dialog("destroy")
				}
			});
			scDialog.dialog('open');
		});

	$("div.aoi_list_cat input[type='checkbox']").click(function () {
		var chk = $(this);

		var text = chk.parents('label').text();
		var value = chk.val();

		if (chk.is(':checked')) {
			$("#selectedcategories").trigger("addItem", { title: text, value: value })
		}
		else {
			$("#selectedcategories").trigger("removeItem", { value: value })
		}
	});

	InitFormWizard(learnerProfileValidationOptions);
	InitCountries();
}

function aoi_select(item) {
	var obj = $.parseJSON(item);
	$("div.aoi_list_cat input[type='checkbox']").filter('input[value=' + obj._value + ']').attr('checked', true);
}

function aoi_remove(item) {
	var obj = $.parseJSON(item);
	$("div.aoi_list_cat input[type='checkbox']").filter('input[value=' + obj._value + ']').attr('checked', false);
}


var learnerProfileValidationOptions =
{
	invalidHandler: validationInvalidHandler,
	rules: {
		FirstName: {
			required: true,
			maxlength: 40
		},
		LastName: {
			required: true,
			maxlength: 40
		},
		HomePhoneNo: {
			maxlength: 20
		},
		WorkPhoneNo: {
			maxlength: 20
		},
		MobileNo: {
			maxlength: 20
		},
		Address: {
			maxlength: 200
		},
		ZipCode: {
			maxlength: 20
		},
		CityName: {
			maxlength: 50
		},
		CountryId: {
			validatecountry: true
		},
		StateId: {
			validatestate: true
		},
		ProvinceId: {
			validateprovince: true
		}
	},
	messages: {
		FirstName: {
			required: "Please write your first name.",
			maxlength: jQuery.format("Please write your first name with a maximum length of {0} characters only.")
		},
		LastName: {
			required: "Please write your last name.",
			maxlength: jQuery.format("Please write your last name with a maximum length of {0} characters only.")
		},
		HomePhoneNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		WorkPhoneNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		MobileNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		Address: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		ZipCode: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		CityName: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		}
	},
	errorPlacement: errorPlacement
}

$.validator.addMethod("validateschedule", function (value, element, params) {
	$dateStart = $("input[id$='DateStart']", $(element).parents(".form-wrapper")).val();
	$dateEnd = $("input[id$='DateEnd']", $(element).parents(".form-wrapper")).val();
	if ($dateStart == "" || $dateEnd == "") {
		return false;
	}
	return true;
}, "Invalid schedule");

function TinyMCEInit() {
	$("textarea[class*='tinymce']").tinymce({
		// Location of TinyMCE script
		script_url: '/content/js/tiny_mce/tiny_mce.js',
		button_tile_map: true,
		encoding: "xml",
		// General options
		theme: "advanced",
		//s_textmetrics is for counting characters
		//plugins: "preview,paste,s_textmetrics",
		//s_textmetrics_on: true,

		plugins: "preview,paste",
		height: "400",
		width: "610",
		content_css: "/content/css/custom_content.css",
		//init_instance_callback: "tinymceInit",

		// Theme options
		//theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,formatselect,fontselect,fontsizeselect,forecolor,backcolor,justifyleft,justifycenter,justifyright,justifyfull",
		theme_advanced_buttons1: "undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,preview",
		theme_advanced_buttons2: "",
		theme_advanced_toolbar_location: "top",
		theme_advanced_toolbar_align: "left",

//        paste_preprocess : function(pl, o) 
//        {    // Replace <div> with <p>
//            o.content = o.content.replace(/<div>/gi, "<p>");    
//            o.content = o.content.replace(/<\/div>/gi, "</p>");
//            o.content = o.content.replace(/<\r\n/gi, "\n");
//            o.content = o.content.replace(/<\n\n/gi, "\n");
//            o.content = o.content.replace(/<\n\n/gi, "\n");
//            
//            // Replace empty styles
//            o.content = o.content.replace(/<style><\/style>/gi, "");    
//            
//            o.wordContent = true;            
//        }

		setup: function (ed) {
			// Display an alert onclick
//            ed.onKeyDown.add(function (ed, e) {
//                if (e.keyCode == 222) {
//                    if (e.preventDefault) e.preventDefault();
//                    e.returnValue = false;
//                    tinyMCE.activeEditor.selection.setContent('`');
//                }
//            });

			ed.onKeyUp.add(function (ed) {
				tinyMCE.triggerSave();
				//                if ($("#aspnetForm").validate().element("#" + ed.id) == true) {
				//                    $("#" + ed.id).parents("td").next("td").children("div").html("");
				//                }
			});

//            ed.onSubmit.add(function (ed, e) {
//                tinyMCE.triggerSave();
//                //                if ($("#aspnetForm").validate().element("#" + ed.id) == true) {
//                //                    $("#" + ed.id).parents("td").next("td").children("div").html("");
//                //                }
//            });

//            ed.onSaveContent.add(function (ed, o) {
//                // Output the element name
//                o.content.replace("&#39;", "&#145;");

//                var content = tinyMCE.get(ed.editorId).getContent();

//                content = content.replace("'", "`");
//                tinyMCE.get(ed.editorId).setContent(content);
//                //moveCursorToEnd(ed.editorId);
//                tinyMCE.activeEditor.focus();
//            });

		},
		valid_styles: { '*': 'text-decoration,text-align' },
		force_br_newlines: true,
		force_p_newlines: false,
		forced_root_block: '', // Needed for 3.x
		valid_elements: ""
			+ "div,"
			+ "strong,"
			+ "b,"
			+ "p[style],"
			+ "em,"
			+ "span[style],"
			+ "ul,"
			+ "li[style],"
			+ "ol,"
			+ "br,"
			+ "blockquote"
	});
}

//function moveCursorToEnd(editor_id) {
//    inst = tinyMCE.getInstanceById(editor_id);
//    tinyMCE.execInstanceCommand(editor_id, "selectall", false, null);
//    if (tinyMCE.isMSIE) {
//        rng = inst.getRng();
//        rng.collapse(false);
//        rng.select();
//    }
//    else {
//        sel = inst.getSel();
//        sel.collapseToEnd();
//    }
//}

function tinymceInit(inst) {
	var ed = inst;

	ed.pasteAsPlainText = true;

	//adding handlers crossbrowser
	if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
		ed.onKeyDown.add(function (ed, e) {
			if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
				ed.pasteAsPlainText = true;
		});
	} else {
		ed.onPaste.addToTop(function (ed, e) {
			ed.pasteAsPlainText = true;
		});
	}
}

function InitCorporateProfile() {
	InitCountries();
	TinyMCEInit();
	InitFormWizard(corporateProfileValidationOptions);
	$("#tabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
	$("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');
}

var corporateProfileValidationOptions =
{
	invalidHandler: validationInvalidHandler,
	rules: {
		CompanyName: {
			required: true,
			maxlength: 95
		},
		CompanyAka: {
			required: true,
			maxlength: 95
		},
		FirstName: {
			required: true,
			maxlength: 40
		},
		LastName: {
			required: true,
			maxlength: 40
		},
		MiddleName: {
			maxlength: 40
		},


		DirectPhoneNo: {
			maxlength: 40
		},
		FaxNo: {
			maxlength: 40
		},
		HomePhoneNo: {
			maxlength: 20
		},
		WorkPhoneNo: {
			maxlength: 20
		},
		MobileNo: {
			maxlength: 40
		},


		JobFunction: {
			maxlength: 40
		},
		Website: {
			maxlength: 190
		},
		UserProfile: {
			maxlength: 19000
		},
		UserOfferedCourses: {
			maxlength: 19000
		},


		Address: {
			maxlength: 200
		},
		ZipCode: {
			maxlength: 20
		},
		CityName: {
			maxlength: 50
		},
		CountryId: {
			validatecountry: true
		},
		StateId: {
			validatestate: true
		},
		ProvinceId: {
			validateprovince: true
		}
	},
	messages: {
		CompanyName: {
			required: "Please write your company name.",
			maxlength: jQuery.format("Please write your company name with a maximum length of {0} characters only.")
		},
		CompanyAka: {
			required: "Please write your company aka.",
			maxlength: jQuery.format("Please write your company aka with a maximum length of {0} characters only.")
		},
		FirstName: {
			required: "Please write your first name.",
			maxlength: jQuery.format("Please write your first name with a maximum length of {0} characters only.")
		},
		LastName: {
			required: "Please write your last name.",
			maxlength: jQuery.format("Please write your last name with a maximum length of {0} characters only.")
		},
		MiddleName: {
			maxlength: jQuery.format("Please write your last name with a maximum length of {0} characters only.")
		},


		DirectPhoneNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		FaxNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		HomePhoneNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		WorkPhoneNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		MobileNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},


		JobFunction: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		Website: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		UserProfile: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		UserOfferedCourses: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},


		Address: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		ZipCode: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		CityName: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		}
	},
	errorPlacement: errorPlacement
}

function plotByDate(from, to) {
	urlDataJSONString = '/Controls/GetCourseVisits/';
	var allDataLines = [];
	$.get(urlDataJSONString, { from: from, to: to }, function (data) {
		dataJSON = $.parseJSON(data);
		var dataLabels = "";
		$.each(dataJSON, function (entryindex, entry) {
			for (var courseVisitType in entry) {
				var dataLinesTemp = entry[courseVisitType];
				var dataLines = [];
				for (var propertyName in dataLinesTemp) {
					var dataPointTemp = dataLinesTemp[propertyName];
					var objectData = [];
					for (var propertyName in dataPointTemp) {
						objectData.push(propertyName);
						objectData.push(dataPointTemp[propertyName]);
					}
					dataLines.push(objectData);
				}
				allDataLines.push(dataLines);
			}
			Plot(allDataLines, dataLabels);
		});
	});
}

function Plot(dataLines, dataLabels) {
	options = {
		title: 'Visits Per Day',

		axesDefaults: {
			show: false,    // wether or not to renderer the axis.  Determined automatically.
			min: null,      // minimum numerical value of the axis.  Determined automatically.
			max: null,      // maximum numverical value of the axis.  Determined automatically.
			pad: 1,       // a factor multiplied by the data range on the axis to give the
							// axis range so that data points don't fall on the edges of the axis.
			ticks: [],      // a 1D [val1, val2, ...], or 2D [[val, label], [val, label], ...]
							// array of ticks to use.  Computed automatically.
			numberTicks: undefined,
			renderer: $.jqplot.LinearAxisRenderer,  // renderer to use to draw the axis,
			rendererOptions: {},    // options to pass to the renderer.  LinearAxisRenderer
									// has no options,
			tickOptions: {
				mark: 'outside',    // Where to put the tick mark on the axis
									// 'outside', 'inside' or 'cross',
				showMark: true,
				showGridline: true, // wether to draw a gridline (across the whole grid) at this tick,
				markSize: 7,        // length the tick will extend beyond the grid in pixels.  For
									// 'cross', length will be added above and below the grid boundary,
				show: true,         // wether to show the tick (mark and label),
				showLabel: true,    // wether to show the text label at the tick,
				formatString: '%.0f'   // format string to use with the axis tick formatter                
			},
			showTicks: true,        // wether or not to show the tick labels,
			showTickMarks: true,    // wether or not to show the tick marks,
			borderColor: 'white'
		},

		axes: {
			xaxis: {
				renderer: $.jqplot.DateAxisRenderer,
				rendererOptions: { tickRenderer: $.jqplot.CanvasAxisTickRenderer },
				tickOptions: {
					formatString: '%m-%d-%Y',
					fontSize: '12px',
					fontFamily: 'Arial',
					angle: -30,
					mark: 'cross',
					showGridline: false
				},
				label: 'Dates',
				tickInterval: '3 Day'
			},
			yaxis: { 
				label: 'Visits', 
				min: 0, 
				numberTicks: 5,
				labelRenderer:  $.jqplot.CanvasAxisLabelRenderer,
				labelOptions: {
					textColor: '#6D869F',
					fontSize: '13px',
					fontFamily: '"Lucida Grande","Lucida Sans Unicode",Verdana,Arial,Helvetica,sans-serif',
					fontWeight: '900'
				}
			}
		},
		legend: { show: true, numberTicks: 5 },
		grid: { background: 'white', gridLineColor: '#c2c2c2', shadow: false },
		
		seriesDefaults: {
			show: true,     // wether to render the series.
			xaxis: 'xaxis', // either 'xaxis' or 'x2axis'.
			yaxis: 'yaxis', // either 'yaxis' or 'y2axis'.
			label: '',      // label to use in the legend for this line.
			color: '',      // CSS color spec to use for the line.  Determined automatically.
			lineWidth: 2, // Width of the line in pixels.
			shadow: true,   // show shadow or not.
			shadowAngle: 45,    // angle (degrees) of the shadow, clockwise from x axis.
			shadowOffset: 1.25, // offset from the line of the shadow.
			shadowDepth: 3,     // Number of strokes to make when drawing shadow.  Each
								// stroke offset by shadowOffset from the last.
			shadowAlpha: 0.1,   // Opacity of the shadow.
			showLine: true,     // whether to render the line segments or not.
			showMarker: false,   // render the data point markers or not.
			fill: false,        // fill under the line,
			fillAndStroke: false,       // *stroke a line at top of fill area.
			fillColor: undefined,       // *custom fill color for filled lines (default is line color).
			fillAlpha: 0.50,       // *custom alpha to apply to fillColor.
			renderer: $.jqplot.LineRenderer,    // renderer used to draw the series.
			rendererOptions: {}, // options passed to the renderer.  LineRenderer has no options.
			markerRenderer: $.jqplot.MarkerRenderer,    // renderer to use to draw the data
														// point markers.
			markerOptions: {
				show: true,             // wether to show data point markers.
				style: 'filledSquare',  // circle, diamond, square, filledCircle.
										// filledDiamond or filledSquare.
				lineWidth: 1,       // width of the stroke drawing the marker.
				size: 7,            // size (diameter, edge length, etc.) of the marker.
				color: 'red',    // color of marker, set to color of line by default.
				shadow: true,       // wether to draw shadow on marker or not.
				shadowAngle: 45,    // angle of the shadow.  Clockwise from x axis.
				shadowOffset: 1,    // offset from the line of the shadow,
				shadowDepth: 3,     // Number of strokes to make when drawing shadow.  Each stroke
									// offset by shadowOffset from the last.
				shadowAlpha: 0.07   // Opacity of the shadow
			}
		},

		series: [
					{ 
						label: 'All', 
						color: '#e68900', 
						showLine: true, 
						markerOptions: {
							show: true,             // wether to show data point markers.                            
							color: '#e68900'    // color of marker, set to color of line by default.                            
						}
					},
					{ 
						label: 'Courses', 
						color: '#008ae6', 
						showLine: true, 
						markerOptions: {
							show: true,             // wether to show data point markers.                            
							color: '#008ae6'    // color of marker, set to color of line by default.                            
						}
					},
					{ 
						label: 'Events', 
						color: '#e6001f', 
						showLine: true, 
						markerOptions: {
							show: true,             // wether to show data point markers.                            
							color: 'red'    // color of marker, set to color of line by default.                            
						}
					}
				],
		
		cursor: { show: false },
		highlighter: {
			show: true,
			lineWidthAdjust: 2.5,   // pixels to add to the size line stroking the data point marker
									// when showing highlight.  Only affects non filled data point markers.
			sizeAdjust: 5,          // pixels to add to the size of filled markers when drawing highlight.
			showTooltip: true,      // show a tooltip with data point values.
			tooltipLocation: 'nw',  // location of tooltip: n, ne, e, se, s, sw, w, nw.
			fadeTooltip: true,      // use fade effect to show/hide tooltip.
			tooltipFadeSpeed: "fast",// slow, def, fast, or a number of milliseconds.
			tooltipOffset: 2,       // pixel offset of tooltip from the highlight.
			tooltipAxes: 'both',    // which axis values to display in the tooltip, x, y or both.
			tooltipSeparator: ' - ',  // separator between values in the tooltip.
			useAxesFormatters: true, // use the same format string and formatters as used in the axes to
									// display values in the tooltip.
			tooltipFormatString: '%.5P' // sprintf format string for the tooltip.  only used if
										// useAxesFormatters is false.  Will use sprintf formatter with
										// this string, not the axes formatters.
		}
	};

	plot = $.jqplot('pageVisits', dataLines, options);
	plot.redraw(); // gets rid of previous axis tick markers
}

function InitPartnerDashboard() {
	$(".date_range #DateStart").datepicker({
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		onSelect: function (dateStr) {
			$(".date_range #DateEnd").datepicker('option', 'minDate', $(this).datepicker('getDate') || '-1m');
		}
	}).mask("99/99/9999");
	$(".date_range #DateEnd").datepicker({
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		onSelect: function (dateStr) {
			$(".date_range #DateStart").datepicker('option', 'maxDate', $(this).datepicker('getDate') || 0);
		}
	}).mask("99/99/9999");
	$('#ui-datepicker-div').wrap('<div class="hasDP"></div>');

	plotByDate("", "");

	$("#update_graph").click(function () {
		plotByDate($(".date_range #DateStart").val(), $(".date_range #DateEnd").val());
		return false;
	});
}

function InitLearnerDashboard() {
	$(".date_range #DateStart").datepicker({
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		onSelect: function (dateStr) {
			$(".date_range #DateEnd").datepicker('option', 'minDate', $(this).datepicker('getDate') || '-1m');
		}
	}).mask("99/99/9999");
	$(".date_range #DateEnd").datepicker({
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		onSelect: function (dateStr) {
			$(".date_range #DateStart").datepicker('option', 'maxDate', $(this).datepicker('getDate') || 0);
		}
	}).mask("99/99/9999");
	$('#ui-datepicker-div').wrap('<div class="hasDP"></div>');
}

function CostNotSpecified() {
	var costnotspecified = $('input#CostNotSpecified').attr("checked");
	var cost = $('input#Cost');
	var costDiv = cost.parents('div.tb_price');
	var currency = $('#CurrencyId');
	var vat = $('#CostVatIncluded');
	if (costnotspecified == true) {
		currency.attr("disabled", "disabled")
		vat.attr("disabled", "disabled")
		cost.attr("disabled", "disabled");
		cost.val('Not Specified');
		cost.toggleClass("disabled", true);
		costDiv.toggleClass("disabled", true);        
	}
	else {
		currency.removeAttr("disabled");
		vat.removeAttr("disabled");
		cost.removeAttr("disabled");
		cost.val('');
		cost.toggleClass("disabled", false);
		costDiv.toggleClass("disabled", false);
	}

	currency.ufd("changeOptions");
	vat.ufd("changeOptions");
}

function InitCourseForm() {

	//init countries
	InitCountries();

	//disables prices
	var costnotspecified = $('input#CostNotSpecified');
	costnotspecified.click(CostNotSpecified);

	//create vertical tabs
	$(".vtabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
	$("#citabs li, #cdtabs li").removeClass('ui-corner-top').addClass('ui-corner-left');

	//init ufd dropdownlist
	var currency = $("#CurrencyId");
	var vatincluded = $("#CostVatIncluded");
	var programtype = $("#ProgramID");
	var method = $("#MethodID");
	var status = $("#StatusID");
	var nodayssched = $("select[id*='Month'], select[id*='Year']");

	//{infix:false,addEmphasis: true}
	currency.ufd({ infix: false });
	vatincluded.ufd({ infix: false });
	programtype.ufd({ infix: false });
	method.ufd({ infix: false });
	status.ufd({ infix: false });
	nodayssched.ufd({ infix: false });    

	//copy category list to end of body to remove it from form tag for validation
	var catList = $('div.course_list_cat');
	$('body').append(catList);
	catList = null;

	$(".coursecat_popupselect a").click(function () {
		var scDialog = $('div.cc_modal_catlist');

		//create share dialog
		scDialog.dialog({
			autoOpen: false,
			resizable: false,
			draggable: false,
			modal: false,
			width: '875px',
			height: '500',
			title: 'Course Categories',
			open: function (event, ui) {
				//copy category list to dialog
				var catList = $('div.course_list_cat');
				scDialog.append(catList);
				catList.show();
				if ($.browser.msie) {
					var selectedCats = $("select#selectedcategories option:selected");
					$("div.course_list_cat input[type='checkbox']").attr('checked', false);
					selectedCats.each(function (index) {
						var chk = "cat" + $(this).val();
						$("#" + chk).attr('checked', true);
					});
				}
				catList = null;
			},
			beforeClose: function (event, ui) {
				//move category list to end of body
				var catList = $('div.course_list_cat');
				catList.hide();
				$('body').append(catList);
				catList = null;
				scDialog.empty();

				scDialog.dialog("destroy")
			},
			buttons: {
				Ok: function () {
					$(this).dialog("close");
				}
			}
		});
		scDialog.dialog('open');
    });

	//add event to category checkboxes that adds the selected item to selected category textbox
	$("div.course_list_cat input[type='checkbox']").click(function () {
		var chk = $(this);

		var text = chk.parents('label').text();
		var value = chk.val();

		if (chk.is(':checked')) {
			$("#selectedcategories").trigger("addItem", { title: text, value: value });
		}
		else {
			$("#selectedcategories").trigger("removeItem", { value: value })
		}            
	});
	
	var chkNoSpecificDay = $('#NoSpecificDay');
	var nospecificday = chkNoSpecificDay.attr('checked');

	var schedWithDay = $(".schedule");
	var schedWithoutDay = $(".nodayschedule").hide();

	//check if course dates has specific day
	if (nospecificday == false) {
		schedWithDay.show();
		schedWithoutDay.hide();
	}
	else {
		schedWithDay.hide();
		schedWithoutDay.show();
	}

	//remove label from all schedules except first
	if (schedWithDay.length > 1) {
		$(".form-label", ".schedule").html("");
		$(".form-label", ".schedule:first").html("Course Dates:");
	}

	//remove label from all schedules except first
	if (schedWithoutDay.length > 1) {
		$(".form-label", ".nodayschedule").html("");
		$(".form-label", ".nodayschedule:first").html("Course Dates:");
	}

	//clears schedule list
	//shows course schedule with/without date depending on checkbox
	chkNoSpecificDay.click(function () {
		var nospecificday = $(this).attr('checked');

		if (nospecificday == false) {
			var sched = $(".schedule").slideDown();
			sched.find(".form-label").html("Course Dates:");
			sched.find(".form-error").html("");

			$(".nodayschedule:first").hide();
			$(".nodayschedule:visible").remove();
			$(".schedule input").removeAttr('disabled');

			//add date validation
			addDateValidation($("[id*='DateStart']", ".schedule:last"));
			addDateValidation($("[id*='DateEnd']", ".schedule:last"));
		}
		else {
			var sched = $(".nodayschedule").slideDown();
			sched.find(".form-label").html("Course Dates:");
			sched.find(".form-error").html("");

			$(".schedule:first").hide();

			$(".schedule:visible").remove();
			$(".schedule input").attr('disabled', 'disabled');

			$(".schedule input").rules("remove");
		}
	});

	//hide remove schedule button
	$(".remove-schedule", ".schedule:first").hide();
	$(".remove-schedule", ".nodayschedule:first").hide();

	$(".remove-schedule").live("click", function () {
		var nospecificday = $('#NoSpecificDay').attr('checked');

		var selector = ".schedule";
		if (nospecificday == true) {
			selector = ".nodayschedule";
		}
		var $scheduleElement = $(this);
		var $scheduleElements = $(selector).length;

		var parent = $scheduleElement.parents(selector);
		var currentIndex = parent.index();
		if (currentIndex != 0) {
			parent.remove();
//            parent.slideUp(500, function () {
//                parent.remove();
//            });
			$(".add-schedule").parent().show();
		}
	});

	var newSchedElemIndex = $(".schedule").length;
	var newNoSchedElemIndex = $(".nodayschedule").length;

	$(".add-schedule").click(function () {
		var nospecificday = $('#NoSpecificDay').attr('checked');

		var $addButton = $(this);

		//check if schedule has day
		if (nospecificday == false) {
			var lastschedule = $(".schedule:last");

			//clone first row of schedule
			lastschedule.clone().appendTo("#schedule-list");
			//lastschedule.hide();
			//lastschedule.slideDown();

			//remove label
			lastschedule = $(".schedule:last");
			lastschedule.find(".form-label").html("");
			lastschedule.find(".form-error").html("");

			//update id and value of index to allow model binder to populate courseschedules list
			lastschedule.find("input[name='CourseSchedules.Index']").val(newSchedElemIndex);
			lastschedule.find(".remove-schedule").show();

			var $whenFields = lastschedule.find("input[type='text']");
			var whenFieldNames = ["DateStart", "DateEnd", "CourseTime"];

			for (i = 0; i < $whenFields.length; i++) {

				var field = $($whenFields[i]);
				field.val('');
				field.attr("id", "CourseSchedules_" + newSchedElemIndex + "__" + whenFieldNames[i]);
				field.attr("name", "CourseSchedules[" + newSchedElemIndex + "]." + whenFieldNames[i]);
				field.removeClass("hasDatepicker");
			}

			//add date picker to textbox
			$($whenFields[0]).datepicker({
				defaultDate: '-0d',
				changeMonth: true,
				changeYear: true,
				onSelect: function (dateStr) {
					$($whenFields[1]).datepicker('option', 'minDate', $(this).datepicker('getDate') || '-1m');
					$(this).blur();
				}
			});

			//add date picker to textbox
			$($whenFields[1]).datepicker({
				defaultDate: new Date(),
				changeMonth: true,
				changeYear: true,
				onSelect: function (dateStr) {
					$($whenFields[0]).datepicker('option', 'maxDate', $(this).datepicker('getDate') || 0);
					$(this).blur();
				}
			});

			//add date validation
			addDateValidation($("[id*='DateStart']", ".schedule:last"));
			addDateValidation($("[id*='DateEnd']", ".schedule:last"));

			newSchedElemIndex++;
		}
		else {

			var firstschedule = $(".nodayschedule:first");

			var dateufd = firstschedule.find('select');
			dateufd.ufd("destroy");

			firstschedule = $(".nodayschedule:first");

			var lastschedule = firstschedule.clone();
			lastschedule.appendTo("#schedule-list");
			//lastschedule.appendTo("#schedule-list").hide().slideDown("slow");
			lastschedule.find(".form-label").html("");
			lastschedule.find(".form-error").html("");

			var ddls = lastschedule.find("select");
			ddls.find("option:first").attr('selected', 'selected');
			//ddls.val(1);

			var dayFields = ["StartMonth", "StartYear", "EndMonth", "EndYear"];
			for (i = 0; i < ddls.length; i++) {
				$(ddls[i]).attr("id", "NoDayCourseSchedules_" + newNoSchedElemIndex + "__" + dayFields[i]);
				$(ddls[i]).attr("name", "NoDayCourseSchedules[" + newNoSchedElemIndex + "]." + dayFields[i]);
			}

			lastschedule.find("input[name='NoDayCourseSchedules.Index']").val(newNoSchedElemIndex);

			dateufd = firstschedule.find('select');
			dateufd.ufd({ infix: false });
			dateufd = null;

			dateufd = lastschedule.find('select');
			dateufd.ufd({ infix: false });

			lastschedule.find(".remove-schedule").show();

			newNoSchedElemIndex++;

		}
		//        if ($scheduleElements > 3) {
		//            $addButton.parent().hide();
		//        }
	});

	//format time when focus leaves textbox
	$("input[id*='ClassTimeFrom'], input[id*='ClassTimeTo']").live('blur', function () {
		var input = $(this);

		var timeInput = input.val();

		if (isNaN(timeInput) == false) {
			var intInput = parseInt(timeInput)
			if (Date.validateHour(intInput) == true) {
				if (intInput >= 6 && intInput < 12) {
					timeInput = timeInput + "am";
				}
				else {
					timeInput = timeInput + "pm";
				}
			}
		}
		var newInput = Date.parse(timeInput).toString('t');

		input.val(newInput);
	});

	//add date pickers
	$("[id*='DateStart']").datepicker({
		defaultDate: '-0d',
		changeMonth: true,
		changeYear: true,
		onSelect: function (dateStr) {
			$("[id*='DateEnd']").datepicker('option', 'minDate', $(this).datepicker('getDate') || '-1m');
			$(this).blur();
		}
	});
	$("[id*='DateEnd']").datepicker({
		defaultDate: new Date(),
		changeMonth: true,
		changeYear: true,
		onSelect: function (dateStr) {
			$("[id*='DateStart']").datepicker('option', 'maxDate', $(this).datepicker('getDate') || 0);
			$(this).blur();
		}
	});

	$("#DeadlineForEnrollment").datepicker({
		defaultDate: '-0d',
		changeMonth: true,
		changeYear: true,
		onSelect: function(dateText, inst){ 
			$(this).blur();
		}
	});

	//wrap datepicker to hasDP div for css layout
	$('#ui-datepicker-div').wrap('<div class="hasDP"></div>');

	//create days buttonset
	$('div.classscheduledays').buttonset();

	$(".remove-classschedule", ".classschedule:first").hide();

	$(".remove-classschedule").bind("click", function () {
		var $scheduleElement = $(this);

		var parent = $scheduleElement.parents(".classschedule");        
		var currentIndex = parent.index();
		if (currentIndex != 0) {
			//parent.html();
			parent.slideUp(500, function () {
				var days = parent.find("div.classscheduledays");
				days.buttonset('destroy');
				parent.remove();
			});
			//$(".add-classschedule").parent().show();
		}
	});

	var newClassSchedIndex = $(".classschedule").length;

	$(".add-classschedule").click(function () {
		var $addButton = $(this);

		var firstschedule = $(".classschedule:first");
		var daysdiv = firstschedule.find('div.classscheduledays');
		daysdiv.buttonset("destroy");
		firstschedule = $(".classschedule:first");

		var lastschedule = firstschedule.clone();
		lastschedule.appendTo("#classschedule-list").hide().slideDown();
		//lastschedule.appendTo("#classschedule-list");

		//alert(lastschedule.html());
		lastschedule.find(".form-label").html("");
		lastschedule.find(".form-error").html("");

		var days = lastschedule.find("input[type='checkbox']");
		var dayslabel = lastschedule.find("label");
		days.removeAttr("checked");

		var dayFields = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
		for (i = 0; i < days.length; i++) {
			$(days[i]).attr("id", "ClassSchedules_" + newClassSchedIndex + "__" + dayFields[i]);
			$(days[i]).attr("name", "ClassSchedules[" + newClassSchedIndex + "]." + dayFields[i]);

			var label = $(dayslabel[i]);
			label.attr("for", "ClassSchedules_" + newClassSchedIndex + "__" + dayFields[i]);
			label.html(label.text());
		}

		var timefrom = lastschedule.find("input[name*='ClassTimeFrom']");
		var timeto = lastschedule.find("input[name*='ClassTimeTo']");

		timefrom.attr("id", "ClassSchedules_" + newClassSchedIndex + "__ClassTimeFrom");
		timefrom.attr("name", "ClassSchedules[" + newClassSchedIndex + "].ClassTimeFrom");
		timefrom.val('');

		timeto.attr("id", "ClassSchedules_" + newClassSchedIndex + "__ClassTimeTo");
		timeto.attr("name", "ClassSchedules[" + newClassSchedIndex + "].ClassTimeTo");
		timeto.val('');

		lastschedule.find("input[name='ClassSchedules.Index']").val(newClassSchedIndex);

		daysdiv = firstschedule.find('div.classscheduledays');
		daysdiv.buttonset();
		daysdiv = null;

		daysdiv = lastschedule.find('div.classscheduledays');
		daysdiv.buttonset();

		lastschedule.find(".remove-classschedule").show();

		newClassSchedIndex++;
	});
	
	InitFormWizard(courseValidationOptions, courseStepShown);
	TinyMCEInit();
	
	removeErrorFromCategories();

	//add date validation
	addDateValidation($("[id*='DateStart']"));    
	addDateValidation($("[id*='DateEnd']"));    

	$("#ci_clickhere").click(function(){
		$("#citabs").tabs('select', 1);
	});

	$("#MethodID").change(function(){
		MethodChanged();
	});    
}

function InitCourseCategorySelection()
{
	$("#selectedcategories").fcbkcomplete({
		json_url: '/categories/search',
		addontab: true,
		height: 5,
		complete_text: 'Type to start..',
		maxshownitems: 15,
		maxitems: 3,
		onselect: ct_select,
		onremove: ct_remove
	});
}

function InitEventCategorySelection()
{
	$("#selectedcategories").fcbkcomplete({
		json_url: '/categories/searcheventcategories',
		addontab: true,
		height: 5,
		complete_text: 'Type to start..',
		maxshownitems: 15,
		maxitems: 3,
		onselect: ct_select,
		onremove: ct_remove
	});
}

function MethodChanged()
{
	if ($("#stepwizardform").formwizard("getCurrentStep") == "step2")
	{
		var method = $("#MethodID").val();
		//disable inputs

		var venue = $("#Venue");
		var roomno = $("#RoomNo");
		var address = $("#Address");
		var state = $("#StateId");
		var province = $("#ProvinceId");
		var city = $("#CityId");
		var zipcode = $("#ZipCode");

		//online method
		if (method == "2")
		{
			venue.attr("disabled", "disabled");
			roomno.attr("disabled", "disabled");
			address.attr("disabled", "disabled");
			state.attr("disabled", "disabled");
			province.attr("disabled", "disabled");
			city.attr("disabled", "disabled");
			zipcode.attr("disabled", "disabled");
			state.html("<option>Not Applicable</option>");
			province.html("<option>Not Applicable</option>");
			city.html("<option>Not Applicable</option>");
		}
		else
		{
			venue.removeAttr("disabled");
			roomno.removeAttr("disabled");
			address.removeAttr("disabled");
			state.removeAttr("disabled");
			province.removeAttr("disabled");
			city.removeAttr("disabled");
			zipcode.removeAttr("disabled");
		}

		state.ufd("changeOptions");
		province.ufd("changeOptions");
		city.ufd("changeOptions");
	}
}

function courseStepShown()
{    
	MethodChanged();
}

function addDateValidation(txt)
{
	txt.rules("add", {
		required: true,
		date: true,
		messages: {
			required: "Invalid schedule",
			date: "Invalid schedule"
		}
	});
}

var selectedCategories = $("div.course_list_cat input[type='checkbox']:checked").length;

function CountSelectedCategories(increment) {
	selectedCategories = selectedCategories + increment;
	if (selectedCategories >= 3) {
		$("div.course_list_cat input[type='checkbox']:not(:checked)").attr("disabled", "disabled");
	}
	else if (selectedCategories == 2) {
		$("div.course_list_cat input[type='checkbox']:not(:checked)").removeAttr("disabled");
	}
}

function ct_select(item) {
	var obj = $.parseJSON(item);
	$("div.course_list_cat input[type='checkbox']").filter('input[value=' + obj._value + ']').attr('checked', true);
	CountSelectedCategories(1);
}

function ct_remove(item) {
	var obj = $.parseJSON(item);
	$("div.course_list_cat input[type='checkbox']").filter('input[value=' + obj._value + ']').attr('checked', false);
	CountSelectedCategories(-1);
}

function nonzero (value, element, params) {
	return this.optional(element) || value == params[0] + params[1];
}

function validationInvalidHandler(form, validator) {        
	for (var i = 0; i <= validator.errorList.length; i++)
	{
		var elem = $(validator.errorList[i].element);
		var step = elem.parents('.vtabs > div');
		var tabholder = elem.parents('.vtabs');
		var index = tabholder.children('div').index(step);

		tabholder.tabs('select', index);
		break;
	}      
}

var courseValidationOptions =
{
	invalidHandler: validationInvalidHandler,
	focusInvalid: false,
	focusCleanup: true,
	rules: {
		CourseTitle: {
			required: true,
			maxlength: 195
		},
		Cost: {
			required: true,
			maxlength: 20
		},
		CurrencyId: {
			required: true
		},
		ProgramID: {
			nonzero: true
		},        
		MethodID: {
			nonzero: true
		},
		StatusID: {
			nonzero: true
		},
		selectedcategories: {
			required: true,
			nonzero: true
		},

		NoOfDays: {
			maxlength: 10
		},
		TotalHours: {
			maxlength: 10
		},
		NoOfParticipants: {
			maxlength: 10
		},
		DeadlineForEnrollment: {
			date: true
		},


		CourseDescription: {
			required: true,
			maxlength: 19500
		},
		CourseDetails: {
			maxlength: 19500
		},
		TrainerName: {
			maxlength: 9500
		},
		SpecialOffer: {
			maxlength: 5500
		},

		Venue: {
			maxlength: 100
		},
		RoomNo: {
			maxlength: 20
		},
		Address: {
			maxlength: 200
		},
		ZipCode: {
			maxlength: 20
		},        
		CountryId: {
			validatecountry: true
		},
		StateId: {
			validatestate: true
		},
		ProvinceId: {
			validateprovince: true
		},
		CityId: {
			validatecity: true
		}
	},
	messages: {
		CourseTitle: {
			required: "Please write the title of your course.",
			maxlength: jQuery.format("Your course title should contain a maximum length of {0} characters.")
		},
		Cost: {
			required: "Please write the cost.",
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		CurrencyId: {
			required:  "Please select a currency."
		},
		ProgramID: {
			nonzero: "Please select a Program Type."
		},
		MethodID: {
			nonzero: "Please select a Methodology."
		},
		StatusID: {
			nonzero: "Please select a Course Status."
		},
		selectedcategories: {
			required: "Please select atleast one category.",
			nonzero: "Please select atleast one category."
		},
		NoOfDays: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		TotalHours: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		NoOfParticipants: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		DeadlineForEnrollment: {
			date: "Please, enter a valid date"
		},


		CourseDescription: {
			required: jQuery.format("Please write a description."),
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		CourseDetails: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		TrainerName: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		SpecialOffer: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},

		Venue: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		RoomNo: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		Address: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		ZipCode: {
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		}
	},
	errorPlacement: errorPlacement
}

function getErrorDiv(element)
{
	var error;
	if (element.hasClass("tinymce") == true) {
		error = element.parents("div.ui-tabs-panel").find("div.error");
	}
	else if (element.hasClass("date_validation_sel") == true) {
		error = element.parents(".form-wrapper").find("div.form-error");
	}
	else {
		error = element.parents("tr").find("div.error");
	}

	return error;
}

function errorPlacement(error, element) {
	var errorDiv = getErrorDiv(element);
	errorDiv.html(error.text());    
}

function removeErrorOnBlur() {    
	$("#stepwizardform div.textbox_div textarea, #stepwizardform div.textbox_div input, input.date_validation_sel, #cp_ajaxform input").blur(function (){
		
		var element = $(this);
		if (element.hasClass("error") == true)
		{
			$("#stepwizardform").validate().element('#' + element.attr('id') );
		}

		if (element.hasClass("valid") == true)
		{        
			var errorDiv = getErrorDiv(element);
			errorDiv.html("");
		}
	});
}

function removeErrorFromCategories()
{
	$('li[id*="selectedcategories"] input.maininput').live('blur', function () {        
		var element = $('#selectedcategories');

		var valid = $("#stepwizardform").validate().element( "#selectedcategories" );

		if (valid == true)
		{        
			var errorDiv = getErrorDiv(element);
			errorDiv.html("");
		}
	});
}

$.validator.addMethod("nonzero", nonzero, "Please select one.");

function nonzero(value, element) {

	var field = $(element);
	var err = field.parents("tr").find('div.error');

	field.hide();
	if (value.length == 0 || value == 0) {
		return false;
	}
	else {
		err.html("");
		return true;
	}
}

function createDeleteConfirmationDialog() {
	
	$(".course_delete_button").live("click", function (event) {
		event.preventDefault();
		var $link = $(this);
		var err = $('<div class="errMessage">');

		err.html("Are you sure?");

		err.dialog({
			resizable: false,
			height: 140,
			modal: true,
			draggable: false,
			title: "Delete Confirmation",
			buttons: {
				"Continue": function () {
					$(this).dialog("close");
					$.post($link.attr("href"), null, reloadPage);
				},
				Cancel: function () {
					$(this).dialog("close");
				}
			}
		});
	});
}
function reloadPage() { location.reload(true); }

function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}

function InitChangePassword() {
	var options = {
		dataType: 'json',
		success: changePasswordSucceed,  // post-submit callback 
		beforeSubmit: validateChangePasswordForm,
		error: changePasswordFailed        
	};

	var form = $('#cp_ajaxform');
	form.ajaxForm(options);

	form.validate(cpValidationOptions);
	removeErrorOnBlur();
}

var cpValidationOptions =
{
	focusInvalid: false,
	focusCleanup: true,
	rules: {
		OldPassword: {
			required: true,
			maxlength: 20
		},
		NewPassword: {
			required: true,
			maxlength: 20
		},
		ConfirmPassword: {
			required: true,
			maxlength: 20
		}
	},
	messages: {
		OldPassword: {
			required: "Please write your old password.",
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		NewPassword: {
			required: "Please write your new password.",
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		},
		ConfirmPassword: {
			required:  "Please write your new password again.",
			maxlength: jQuery.format("Please, enter a max of {0} characters only")
		}
	},
	errorPlacement: errorPlacement
}

function validateChangePasswordForm(formData, jqForm, options) {
	// formData is an array of objects representing the name and value of each field 
	// that will be sent to the server;  it takes the following form: 
	// 
	// [ 
	//     { name:  username, value: valueOfUsernameInput }, 
	//     { name:  password, value: valueOfPasswordInput } 
	// ] 
	// 
	// To validate, we can examine the contents of this array to see if the 
	// username and password fields have values.  If either value evaluates 
	// to false then we return false from this method.

	var errorDiv = $("div.errorList");

	var error = "";

	for (var i = 0; i < formData.length; i++) {
		if (!formData[i].value) {
			error = 'All fields are required';
			errorDiv.html(error);
			return false;
		}        
	}

	var newPass = $("#NewPassword").val();
	var confirmPass = $("#ConfirmPassword").val();

	if (newPass != confirmPass)
	{
		errorDiv.html("New Password and Confirm Password must be the same");
		return false;
	}

	var submit = $('.form_buttons input[type="submit"], .ajax_form button[type="submit"]');

	submit.attr('disabled', 'disabled');
	submit.toggleClass('form_disabled');

	$("span.regform_loader").show();    
	
	//insert validation logic here


	//    for (var i = 0; i < formData.length; i++) {
	//        if (!formData[i].value) {
	//            alert('Please enter a value for both Username and Password');
	//            return false;
	//        }
	//    }
	//    alert('Both fields contain values.');

}

function changePasswordSucceed(data) {
	//window.location.replace("/learners/registrationsuccessful");
	var errorDiv = $("div.errorList");
	errorDiv.html(data.Message);
	errorDiv.show();

	var submit = $('.form_buttons input[type="submit"]');

	submit.removeAttr('disabled');
	submit.toggleClass('form_disabled');

	$("span.regform_loader").hide();

	$('#cp_ajaxform input[type="password"]').val('');
}


function changePasswordFailed(result, textStatus, errorThrown) {
	var errorDiv = $("div.errorList");
	errorDiv.html(result.responseText);
	errorDiv.show();

	var submit = $('.form_buttons input[type="submit"]');

	submit.removeAttr('disabled');
	submit.toggleClass('form_disabled');

	$("span.regform_loader").hide();
}
