/*
 * Macquarie MGL/AU Utilities JavaScript
 *
 * http://macquarie.com.au
 *
 * Copyright (c) 2010 - Macquarie Group
 */

pageToolsEmailLink = "/mgl/au/business/forms/email-page-form?height=500&amp;width=560&amp;modal=true";

var validator;
$(document).ready(function(){
    wrapInputForms();
    jQuery.validator.setDefaults({
        success: function(label){
            label.text("&nbsp").addClass("success");
        },
        errorPlacement: function(error, element){	
			var currentRadioVal=element.parents("td:first").find("input:radio:checked, input:checkbox:checked").val();
            if (element.parents("td").find(".errorWrapper").size() == 0) {
                if (element.parents("td").size() > 1) {
                    element.parents("td:first").parents("td:first").wrapInner('<li class="labelElement" />').wrapInner('<ul class="errorWrapper" />');
                }
                else {
                    if (element.parents("td:first").children(":first").is("div")) {
                        element.parents("td:first").children(":first").wrapInner('<li class="labelElement" />').wrapInner('<ul class="errorWrapper" />');
                    }
                    else {
												
                        element.parents("td:first").wrapInner('<li class="labelElement" />').wrapInner('<ul class="errorWrapper" />');
						
                    }
                }
                element.parents("ul:first").append('<li class="errorElement"></li>');
				
            }
            element.parents("ul:first").children("li.errorElement").html(error.html());
			element.parents("td:first").find('input:radio[value="'+currentRadioVal+'"], input:checkbox[value="'+currentRadioVal+'"]').attr("checked","checked");
		}
    });
	$(".videoLink").after("<span class='videoLinkIcon'> </span>");
})


$(window).load(function(){emailPageConfirmation()});

function wrapInputForms(){
    $("input.defaultInputSize,input.smallInputSize,input.mediumInputSize,input.largeInputSize").wrap('<span class="textWrapper" />').wrap("<span />");
    $("textarea.defaultInputSize").wrap('<span class="textAreaWrapper" />');
}

function initialiseValidator(){
    validator = $("#formId").validate({
        rules: {
            username: "required",
            email: {
                required: true,
                email: true
            },
            recipient: "required",
            recipientEmail: {
                required: true,
                email: true
            },
            captchaID: "required",
            termsOfUse: "required"
        },
        messages: {
            userName: "Enter your name",
            email: {
                required: "Please enter an email address",
                minlength: "Please enter a valid email address"
            },
            recipient: "Enter a recipient",
            recipientEmail: {
                required: "Please enter a recipient email address",
                minlength: "Please enter a valid recipient email address"
            },
            captchaID: " ",
            termsOfUse: "Please accept the terms of use"
        },
        success: function(label){
            label.html("&nbsp;").addClass("checked");
        }
    });
}

var validationUtils = {
    sendEmailFormValidation: function(formId, captchaImageId, captchaId){
        var captchaValidationUrl = "/vgn-ext-templating/FormAction?captchaCheck=" + escape($("#" + captchaId).val());
        try {
            $.ajax({
                url: captchaValidationUrl,
                context: document,
                success: function(data){
                    if (data != "1") {
                        var numRand = Math.floor(Math.random() * 100000);
                        var newImage = "/vgn-ext-templating/Captcha?random=" + numRand;
                        $("#" + captchaImageId).attr("src", newImage);
                        return false;
                    }
                    else {
                        var titleTag = $("title").html();
                        if (titleTag && jQuery.trim(titleTag) != "") {
                            $("#emailPageName").val(titleTag);
                        }
                        else {
                            $("#emailPageName").val(location.href);
                        }
						if(location.href.indexOf('?')!= -1){
								$("#emailPageAddress").val(location.href+"&rc=1");		
							} else {
								$("#emailPageAddress").val(location.href+"?rc=2");		
							}						                  
						
						//Added to capture the page address in order to redirect to the initial page
						$.cookie("VC-emailPage-startPage",location.href,{path:'/mgl/au',expires:1});
					
						if($.trim($("#message").val())!=""){$("#message").val("Message from " + $("#username").val() +": " + $("#message").val());}					
					
                        document.getElementById("formId").submit();
                    }
                }
            });
        } 
        catch (err) {
            txt = "There was an error on this page.\n\n";
            txt += "Error description: " + err.description + "\n\n";
            txt += "Click OK to continue.\n\n";
            alert(txt);
            return false;
        }
        return false;
    }
}
function validateEmailForm(){
    initialiseValidator();
    if (validator.form()) {
        validationUtils.sendEmailFormValidation("formId", "captchaImage", "captchaID");
    }
}
 

function emailPageConfirmation(){
	var emailFormStartPage = $.cookie("VC-emailPage-startPage")
	if (emailFormStartPage) {
		if (s.getQueryParam("displayEmailSentConfirmation")) {
			var url = "/mgl/au/business/forms/email-page-form/confirmation?height=400&width=560&modal=true";
			tb_show("My Caption", url);
		} else if(s.getQueryParam("displayEmailSentMissingDetails")) {
			var url = "/mgl/au/business/forms/email-page-form/missing-details?height=400&width=560&modal=true";
			tb_show("My Caption", url);
		} 
		$.cookie("VC-emailPage-startPage",null,{path:'/mgl/au',expires:1});
	}}
			
function initPageTools(){$(".VC-pagetools").html('<a class="emailPage thickbox" onclick="om_calculator(\'Email page\')" href="' + pageToolsEmailLink + '"><img class="tooltip" src="/dafiles/Internet/mgl/au/furniture/images/icons/pagetool_email_icon.gif" alt="Email icon" title="Email page"/></a><a class="printPage" href="" onclick="om_calculator(\'Print page\')" ><img class="tooltip" src="/dafiles/Internet/mgl/au/furniture/images/icons/pagetool_print_icon.gif"alt="Printer icon"title="Print page"/></a>');}

function wrapInputForms(){
    $("input.defaultInputSize,input.smallInputSize,input.mediumInputSize,input.largeInputSize").wrap('<span class="textWrapper" />').wrap("<span />");
    $("textarea.defaultInputSize").wrap('<span class="textAreaWrapper" />');
}
