$(document).ready(function () {
    //# Start ektron #
    // main nav rollover drop downs
    $('#mainNav li').hover(function () {
        $(this).addClass('hover');
        $('div', this).show();
    },
	function () {
	    $(this).removeClass('hover');
	    $('div', this).hide();
	});

    // h2.memberServices drop down
    $('h2.memberServices').hover(function () {
        $(this).addClass('hover');
        $('div', this).show();
    },
	function () {
	    $(this).removeClass('hover');
	    $('div', this).hide();
	});
    //## End ektron ##

    //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    //## Start Global ##    
    $.sifr({
        path: "/flash/",
        save: true
    });
    
    $(".homeHeader h1").sifr({
        font: "bliss2light",
        color: "#FFF",
        height: 76,
        width: 570
    });
    
     /*$(".homeHeader ul li a").sifr({
        font: "bliss2",
        color: "#a0d4f7",
        height: 20,
        width: 522
    });*/
    
     $(".contentHeader h1").sifr({
        font: "bliss2light",
        color: "#FFF",
        height: 43,
        width: 570
    });
   
    $(".heading2").sifr({
        font: "bliss2bold",
        color: "#6f6251",
        height: 22
    });

    var clientID = "ctl00_LeftPlaceHolder_"

    //login
    if ($('#ctl00_uxML_UserName').length > 0) {
        $('#ctl00_uxML_UserName').focus();
    }

    //forgot password - causes tooltip to throw error as focus dose not fire tooltip
    //if ($('#ctl00_LeftPlaceHolder_UserName').length > 0) {
    //    $('#ctl00_LeftPlaceHolder_UserName').focus();
    //}

    //register - causes tooltip to throw error as focus dose not fire tooltip
    //if ($('#ctl00_LeftPlaceHolder_FirstName').length > 0) {
    //    $('#ctl00_LeftPlaceHolder_FirstName').focus();
    //}

    $(".anchorFriend").click(function () {
        var url = "/SendToFriend.aspx"; //parent.location.protocol == "http:" ? "/SendToFriend.aspx" : "SendToFriend.aspx";
        dialog({ id: '#friend-dialog', title: 'Send to a friend', modal: true, height: 450, width: 630, autoOpen: true, draggable: true, resizable: false, showButtons: false, hideTitleBar: false, html: '<iframe id="friend-dialog" width="600" height="400" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="no" src="' + url + '"/>', closeBlur: true });
    });

    //this handles all error messages with dialogue
    if ($("#ctl00_ErrorMsg").val()) {
        dialog({ id: '#dialog-message', title: 'Alert', width: 300, height: 100, modal: true, autoOpen: true, draggable: false, resizable: false, showButtons: true, appendEl: '<div id=\"dialog-message\"></div>', html: $("#ctl00_ErrorMsg").val() });
        $("#ctl00_ErrorMsg").val('');
    }

    //## End Global ##

    //## Start Members ##

    //## Start File Upload ##
    if ($("#" + clientID + "UploadedFiles").length > 0) {
        //# see avant-utils.js
        fileUpload();

        if ($("#" + clientID + "UploadedFiles").val()) {
            var files = $("#" + clientID + "UploadedFiles").val().split(",");

            for (i = 0; i < files.length - 1; i++) {
                $("<li/>").appendTo("#uploaded").html(files[i]);
            }
        }
    };
    
    //## Start File Upload ##
    //MS - 20111223 - refactor infuture and store clientId in hidden field
    if ($("#" + clientID + "UploadedFiles").length > 0) {
       fnFileUpload(clientID, null);
    };
    
    if($("#ctl00_LeftPlaceHolder_uxContentBlock_ctl00_UploadedFiles").length > 0)
    {
   
        var cID = "ctl00_LeftPlaceHolder_uxContentBlock_ctl00_";  
        
        if(!$("#" + cID + "MemberNumber").val())
          $(".uploaddisable").prepend("<div id='disablemask' style='display:block;width:110px;background-color:#fff;opacity:0.5;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=30);filter: alpha(opacity=30);height:30px;float:left;z-index:999;position:absolute;'></div>");
         
        //catch all
        $(".uploaddisable").bind("click", function(){
            if(!$("#" + cID + "MemberNumber").val())
            {
              $("#file-uploader-error").show().empty().append("<span style='color:red'>Please enter your Member Number first<span>");
              $("#" + cID + "MemberNumber").focus().addClass('error');
            }
            else{
              $("#disablemask").hide();
            
            }
        });
        
        $("#" + cID + "MemberNumber").blur(function(){
          if($("#" + cID + "MemberNumber").val()){
            $("#" + cID + "MemberNumber").removeClass('error');
            $("#disablemask").hide();  
            $("#file-uploader-error").hide();
            
           //note this is duplicated as i need to call the function again to pass upload 
           var args = {
            element: $('#file-uploader')[0],
            action: '/uploads/process.ashx',
            params: { memberNo: $("#" + cID + "MemberNumber").val(), uploadDir: $('#UploadPath').val() },
            allowedExtensions: ['doc','docx','pdf'],
            clientID: cID
            };
            
            fileUpload(args);
          }
          else
          {
            $("#" + cID + "MemberNumber").addClass('error');
            $("#disablemask").show();
            $("#file-uploader-error").show();
          }
        });
        
        $("#" + cID + "MemberNumber").keyup(function(){
          if(!$("#" + cID + "MemberNumber").val())
            $("#disablemask").show();  
        });
        
       var args = {
            element: $('#file-uploader')[0],
            action: '/uploads/process.ashx',
            params: { memberNo: $("#" + cID + "MemberNumber").val(), uploadDir: $('#UploadPath').val() },
            allowedExtensions: ['doc','docx','pdf'],
            clientID: cID
        };
        
        fnFileUpload(cID, args)
    }
    
    function fnFileUpload(clientID, args)
    {
        fileUpload(args);
        if ($("#" + clientID + "UploadedFiles").val()) {
            var files = $("#" + clientID + "UploadedFiles").val().split(",");

            for (i = 0; i < files.length - 1; i++) {
                $("<li/>").appendTo("#uploaded").html(files[i]);
            }
        }
    }

    //check if memberNumber exists
    /*  if(!$("#" + cID + "MemberNumber").val())
      {
         $("#fileUpload").attr('disabled',true);
      }*/
        
    //## End File Upload ##

    //# Start - Change my category of practice
    var fieldsUpdateAddress = ['Address', 'Suburb', 'State', 'PostCode', 'TelephoneNumber'];

    $("#" + clientID + "PrimaryOrAdditionalPracticeChanged").change(function (index) {
        if ($("#" + clientID + "PrimaryOrAdditionalPracticeChanged").val() == "Yes") {

            $.each(fieldsUpdateAddress, function (index, value) {
                $("#" + clientID + value).addClass("required")
            });
        }
        else {
            $.each(fieldsUpdateAddress, function (index, value) {
                $("#" + clientID + value).removeClass("required");
            });
        }
    });

    //# End - Change my category of practice

    //# Start - Practitioner Indemnity Insuurance
    var fieldsPatient = ['PatientName', 'PatientGender', 'PatientDOB', 'PatientDateFirstSeen', 'PatientDateFirstSeen', 'PatientDateLastSeen', 'PatientIllness', 'PatientIncidentOccured_Y', 'PatientPublicPrivate'];

    if ($("#" + clientID + "Relate_Y").attr('checked') == true) {

        $.each(fieldsPatient, function (index, value) {
            $("#" + clientID + value).addClass("required")
        });
        $("#PatientDetails").show();
    }
    else {
        $.each(fieldsPatient, function (index, value) {
            $("#" + clientID + value).removeClass("required")
        });
        $("#PatientDetails").hide();
    }

    $("#" + clientID + "Relate_Y").click(function (event) {
        $.each(fieldsPatient, function (index, value) {
            $("#" + clientID + value).addClass("required")
        });
        $("#PatientDetails").show();
    });

    $("#" + clientID + "Relate_N").click(function (event) {
        $.each(fieldsPatient, function (index, value) {
            $("#" + clientID + value).removeClass("required")
        });

        $("#" + clientID + "PatientHospitalTypePublic").removeClass("required");
        $("#" + clientID + "PatientHospitalTypePublic").removeClass("error");

        $("#PatientDetails").hide();

    });


    $("#" + clientID + "PatientIncidentOccured_Y").click(function (index) {
        $("#" + clientID + "PatientHospitalTypePublic").addClass("required");
    });

    $("#" + clientID + "PatientIncidentOccured_N").click(function (index) {
        $("#" + clientID + "PatientHospitalTypePublic").removeClass("required");
        $("#" + clientID + "PatientHospitalTypePublic").removeClass("error");
    });

    $("#" + clientID + "PreviouslyReported_Y").click(function (index) {
        if ($("#" + clientID + "PreviouslyReported_Y").attr('checked') == true) {

            $("#" + clientID + "NameOfInsurer").addClass("required");
        }
    });

    $("#" + clientID + "PreviouslyReported_N").click(function (index) {
        if ($("#" + clientID + "PreviouslyReported_N").attr('checked') == true) {
            $("#" + clientID + "NameOfInsurer").removeClass("required");
            $("#" + clientID + "NameOfInsurer").removeClass("error");

            //need to write a function to remove label when deselected
        }
    });

    //# End - Practitioner Indemnity Insuurance

    //# Start - Practice Indemnity Insuurance

    $("#personDiv").EnableMultiField({
        addEventCallback: addCallBack,
        enableRemove: true,
        linkClass: "addMoreFields",
        linkText: "",
        removeLinkText: "",
        removeLinkClass: "removeFields",
        confirmOnRemove: true,
        confirmationMsgOnRemove: "Remove Person?"
    });

    function addCallBack(elem, mainElem) {
        curElm = $(elem);
        $(curElm).find(".date-picker").removeClass("hasDatepicker");
        $(curElm).find(".ui-datepicker-trigger").hide();

        $(function () {
            $(curElm).find(".date-picker").datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'dd/mm/yy',
                showAnim: 'fold',
                showButtonPanel: false,
                yearRange: '1900:' + year,
                showOn: "button",
                buttonImage: "/images/calendar.gif",
                buttonImageOnly: true
            });
        });
    }

    var fieldsPracticePrevInsurer = ['NameofOtherInsurer', 'DateReported'];

    $("#" + clientID + "IsInsurerReport_Y").click(function (index) {
        $.each(fieldsPracticePrevInsurer, function (index, value) {
            $("#" + clientID + value).addClass("required")
        });
    });

    $("#" + clientID + "IsInsurerReport_N").click(function (index) {
        $.each(fieldsPracticePrevInsurer, function (index, value) {
            $("#" + clientID + value).removeClass("required")
        });
    });


    if ($("#" + clientID + "IsInsurerReport_Y").attr('checked') == true) {

        $.each(fieldsPracticePrevInsurer, function (index, value) {
            $("#" + clientID + value).addClass("required")
        });
    }
    else {
        $.each(fieldsPracticePrevInsurer, function (index, value) {
            $("#" + clientID + value).removeClass("required")
        });
    }

    //# End - Practice Indemnity Insuurance ##

    //# Start - Obtain Proof Of Insurance ##
    $("#" + clientID + "DeliveryMethod").change(function (index) {

        if ($("#" + clientID + "DeliveryMethod :selected").text() == "Fax") {
            $("#" + clientID + "FaxNumber").addClass("required");
            $("#" + clientID + "FaxNumber").val($("#Fax").val());
        }
        else {
            $("#" + clientID + "FaxNumber").removeClass("required");
            $("#" + clientID + "FaxNumber").val("");
        }

        if ($("#" + clientID + "DeliveryMethod :selected").text() == "Email") {
            $("#" + clientID + "EmailAddress").addClass("required");
            $("#" + clientID + "EmailAddress").val($("#Email").val());
        }
        else {
            $("#" + clientID + "EmailAddress").removeClass("required");
            $("#" + clientID + "EmailAddress").val("");
        }
    });
    //# End - Obtain Proof Of Insurance ##

    //## End Members ##

    //## Start - LOGIN - ##

    $("#ctl00_uxML_UserName").focus(function (event) {
        $("#ctl00_uxML_UserName").val("");
    });

    $("#ctl00_uxML_Password").focus(function (event) {
        $("#ctl00_uxML_Password").val("");
    });

    //## End - LOGIN - ##



    //## life insurance ##
    //used for scroll back position quick quote
    if ($('div').hasClass('amount')) {
        $("html").scrollTop(1000);
    }
    
     $('a.jsMyDocuments').bind('click', function (event) {
        event.preventDefault();
        var iframe = document.createElement("iframe");
        iframe.src = "/Members/Documents.aspx?docId=" + $(this).attr('id') + "&fileName=" + $(this).attr('title');
        iframe.style.display = "none";
        document.body.appendChild(iframe);
    });

    $('a.jsRenewalPack').bind('click', function (event) {
        event.preventDefault();
        var iframe = document.createElement("iframe");
        iframe.src = "/Members/Documents.aspx?memId=" + $(this).attr('id');
        iframe.style.display = "block";
        document.body.appendChild(iframe);
    });

    $('a.jsConfirmCert').bind('click', function (event) {
        event.preventDefault();
        var iframe = document.createElement("iframe");
        iframe.src = "/Members/Documents.aspx?memId=" + $(this).attr('id') + "&type=confirm-cert";
        iframe.style.display = "none";
        document.body.appendChild(iframe);
    });
    
    $('form').submit(function(){
        if ($(this).valid()){
          var $dlg = launchOverlay();
          $dlg.dialog('open');
          $dlg.parent().find('.ui-widget-header').remove();
          $dlg.parent().addClass('process');
        }    
     });
});
