﻿var hook = function(section) {
    var f = $el("uploadForm");
    var r = $el("recaptchaRefresh");
    var v = $el("recaptchaVoteRefresh");
    var s = $el("submitUpload");
    //var t = $el("type");

    if (r != null) {
        r.onclick = function() {
            return recaptcha("recaptchaImage");
        }
    }

    if (v != null) {
        v.onclick = function() {
            return recaptcha("recaptchaVoteImage");
        }
    }

    if (f != null) {
        f.onsubmit = function() {
            var errors = validate(section);

            showErrors(errors);

            return errors.length == 0;
        }
    }

//    if (t != null) {
//        t.onchange = function() {
//            layout(this.value.toLowerCase());
//        }
//        layout(t.value.toLowerCase())
//    }
    

    datePicker();

}

var datePicker = function()
{

	$(document).ready(function(){
		$("#dob").attr("autocomplete", "off");
		$.datepicker.setDefaults($.datepicker.regional['']);

		var lang = $.datepicker.regional[_region]

		if(typeof lang === "object")
		{
			$("#dob").datepicker(lang);
		}
		$("#dob").datepicker({
			dateFormat: 'dd/mm/yy',
			changeYear: true,
			yearRange: "-40:+0",
			onOpen: function(){
				$(".ui-datepicker").addClass("ui-datepicker-enabled-select");
			},
			onClose: function(){
				$(".ui-datepicker").removeClass("ui-datepicker-enabled-select");
			},
			onChangeMonthYear:function(){
				$(".ui-datepicker").addClass("ui-datepicker-enabled-select");
			}
		});
	});

}

//var replaceMediaTypeSelect = function()
//{

//	$("#inp_type").append("<ul id=\"typePretty\"></ul>");

//	$("#type option").each(function(){
//		var t = $(this).attr("value");
//		$("#typePretty").append("<li class=\"li-" + t + "\"><span class=\"off\"><img src=\"/Content/Image/choose-" + $(this).attr("value") + ".png\" /></span><span class=\"on\"><img src=\"/Content/Image/choose-" + $(this).attr("value") + "-on.png\" /></span></li>");
//		$("#typePretty .li-" + t + " span.off img").click(function(){
//			updateMediaTypeSelect(t);
//		});
//	});

//	$("#type").hide();

//}

//var updateMediaTypeSelect = function(val)
//{
//	$("#typePretty li").removeClass("active");
//	$("#typePretty li.li-" + val).addClass("active");
//	$("#type").val(val);
//	layout(val.toLowerCase());
//}

var replaceSubmits = function(root)
{

	if(root == null)
	{
		root = document
	}

	var submits = root.getElementsByTagName("input");
	var i;

	for(i = 0; i < submits.length; i++)
	{
		if(submits[i].type == "submit" || submits[i].type == "button")
		{
			if(submits[i].style.display != "none")
			{
				var b = cls(submits[i].className, "not-link")

				var back = cls(submits[i].className, "back-style");

				var extra;

				extra = "";
				
				if(back)
				{
					extra = "back-style";
				}

				if(!b)
				{
					replaceSubmitElement(submits[i], extra);
				}
			}
		}
	}

}

var replaceRecaptchaSubmits = function(root)
{
	var submits = root.getElementsByTagName("input");
	var i;

	for(i = 0; i < submits.length; i++)
	{
		if(submits[i].type == "submit" || submits[i].type == "button")
		{
			if(submits[i].style.display != "none")
			{
				replaceSubmitElement(submits[i], null);
			}
		}
	}
}

var replaceSubmitElement = function(el, extra)
{
	var a = replacementLink(el.value, extra);

	if(el.onclick == null)
	{
		a._target = el;
		a.onclick = function()
		{
			this._target.click();
		}
	}
	else
	{
		a._click = el.onclick;
		a.onclick = function()
		{
			this._click();
		}
	}
	if(extra != null)
	{
		a.className += " " + extra;
	}
	el.parentNode.insertBefore(a, el);
	el.style.display = "none";
}

var _controls = [
	{name:"name", val:"req", msg:"ErrorNameMissing"},
	{name:"dob", val:"req", msg:"ErrorDobNotProvided"},
	{name:"email", val:"req", msg:"ErrorEmailMissing"},
	{name:"email", val:"email", msg:"ErrorInvalidEmail"},
	{name:"region", val:"req", msg:"ErrorRegionMissing"},
	{name:"title", val:"req", msg:"ErrorTitleMissing"},
	{name:"recaptcha", val:"req", msg:"ErrorCaptchaMissing"},
	{name:"terms", val:"checked", msg:"ErrorTermsNotMet"},
	{ name: "text", val: "req", msg: "ErrorTextMissing", dep: { name: "type", val: "exact", comp: "text"}}];

var _controlsRecommended = [
	{name:"name", val:"req", msg:"ErrorNameMissing"},
	{name:"dob", val:"req", msg:"ErrorDobNotProvided"},
	{name:"email", val:"req", msg:"ErrorEmailMissing"},
	{name:"email", val:"email", msg:"ErrorInvalidEmail"},
	{name:"region", val:"req", msg:"ErrorRegionMissing"},
	{name:"recommendation", val:"req", msg:"ErrorRecommendationMissing"},
	{name:"title", val:"req", msg:"ErrorTitleMissing"},
	{name:"recaptcha", val:"req", msg:"ErrorCaptchaMissing"},
	{name:"terms", val:"checked", msg:"ErrorTermsNotMet"},
	{name:"text", val:"req", msg:"ErrorTextMissing", dep:{name:"type", val:"exact", comp:"text"}} ];

var _controlsVote = [
	{name:"recaptchaVote", val:"req", msg:"ErrorCaptchaMissing"}];

var validate = function(section)
{
	var i = 0;
	var errors = [];

	var controls = _controls;

	switch(section)
	{
		case "YourWay":
			controls = _controls;
			break;
		case "Recommended":
			controls = _controlsRecommended;
			break;
		case "Vote":
			controls = _controlsVote;
			break;
	}

	for(i = 0; i < controls.length; i++)
	{
		var t = controls[i].name;
		var v = controls[i].val;
		var msg = controls[i].msg;
		var val = controls[i].comp;
		var depend = controls[i].dep;

		var condition = false;
		var valid = false;

		if(depend !== undefined)
		{
			condition = validateItem(depend.name, depend.val, depend.comp);
			if(condition)
			{
				valid = validateItem(t, v, val);
			}
			else
			{
				valid = true;
			}
		}
		else
		{
			valid = validateItem(t, v, val);
		}
		if(!valid)
		{
			var target = $el(t);
			if(target != null)
			{
				errors[errors.length] = { id: t, message: msg, fromStringtable: true};
			}
		}

	}

	// focus if required
	if(errors.length > 0)
	{
		var uid = errors[0].id;
		var t = $el(uid);
		if(t != null)
		{
			if(t.style.visibility != "hidden")
			{
				$el(uid).focus();
			}
		}
	}

	return errors;

}

var validateItem = function(target, validate, value)
{
	var error = $el("inp_" + target + "_errormessage");
	var container = $el("inp_" + target);
	var t = $el(target);

	// hide error message if present

	if(error != null)
	{
		error.style.display = "none";
	}

	if(container == null)
	{
		return;
	}

	removeClass(container, "errored")

	// don't validate hidden items
	if(container.style.display == "none")
	{
		return true;
	}

	switch(validate)
	{
		case "req":
			return t.value != "";
			break;
		case "email":
			var val;
			val = t.value;
			if(typeof(val) == "undefined")
			{
				return false;
			}
			if(val.indexOf("@") == -1)
			{
				return false;
			}
			if(val.length < 4)
			{
				return false;
			}
			return true;
			break;
		case "checked":
			return t.checked;
			break;
		case "exact":
			return t.value === value;
			break;
	}

}

//var layout = function(type)
//{
//	var t = $el("inp_text");
//	var f = $el("inp_file");
//	var d = $el("inp_description");

//	type = type.toLowerCase();

//	if(type == "text")
//	{
//		t.style.display = "block";
//		f.style.display = "none";
//		d.style.display = "none";
//	}
//	else
//	{
//		f.style.display = "block";
//		t.style.display = "none";
//		d.style.display = "block";
//	}

//}

var showErrors = function(errors)
{
	var i;

	if(errors.length == 0)
	{
		return;
	}

	// highlight all errors
	for(i = 0; i < errors.length; i++)
	{
		var t = $el("inp_" + errors[i].id);
		if(t != null)
		{
			if(t.style.display != "none")
			{
				addClass(t, "errored")
			}
		}
	}

	if(typeof displayMobileErrorTooltip != "undefined")
	{
		displayMobileErrorTooltip(errors[0]);
	}
	else
	{
		displayErrorTooltip(errors[0]);
	}
}

var displayErrorTooltip = function(obj)
{
	// show message for first error
	t = $el("inp_" + obj.id);

	if(t != null)
	{
		var msg = $el("inp_" + obj.id + "_errormessage");
		if(msg != null)
		{
			msg.parentNode.removeChild(msg);
		}
		var error = ne("div");

		error.id = "inp_" + obj.id + "_errormessage";
		error.className = "error-message";

		var sp = ne("span");

		if(obj.fromStringtable)
		{
			sp.appendChild(tn($so(obj.message)));
		}
		else
		{
			sp.appendChild(tn(obj.message));
		}

		error.appendChild(sp);

		t.insertBefore(error, t.firstChild);
	}
}

var recaptcha = function(id)
{

	if(id == null)
	{
		id = "recaptchaImage";
	}

	var i = $el(id);

	if(i != null)
	{
		var d = new Date();
		var s = "$el(\""+id + "\").src = \"\/Recaptcha.ashx?d=" + d.valueOf() + "\"";
		setTimeout(s, 100);
		return false;
	}
	return true;
}
