// Press area downloads - Thumbnail rollover previews
this.imagePreview = function(){
    /* CONFIG */

        xOffset = -490;
        yOffset = 280;

        // these 2 variable determine popup's distance from the cursor
        // you might want to adjust to get the right result

    /* END CONFIG */
    $("a.preview").hover(function(e){
        this.t = this.title;
        this.title = "";
        var c = (this.t != "") ? "<br/>" + this.t : "";
        $("body").append("<p id='preview'><img src='"+ this.rel +"' alt='Loading Image preview...' />"+ c +"</p>");
        $("#preview")
            .css("top",(e.pageY - yOffset) + "px")
            .css("left",(e.pageX + xOffset) + "px")
            .fadeIn("fast");
    },
    function(){
        this.title = this.t;
        $("#preview").remove();
    });
    $("a.preview").mousemove(function(e){
        $("#preview")
            .css("top",(e.pageY - yOffset) + "px")
            .css("left",(e.pageX + xOffset) + "px");
    });
};





$(document).ready(function() {

        imagePreview();

        $.fn.slideFadeToggle = function(speed, easing, callback) {
            return this.animate({height: 'toggle'}, speed, easing, callback);
        };


        /////////////////////////////////////////////
        // Left navigation panels

        $(".panel > ul").hide(); // Close all panels
        $("#open > ul").show();  // Re-open the panel for whichever section current page is in

        $(".panel span").click(function () {

                $panel = $(this).parent().attr("id");

                // Only close/open other section panels
                if ($panel != "open") {
                        $(this).parent().children("ul").slideToggle("medium", "easeOutSine").addClass('selected');
                }

                // Loops through each panel and closes any open ones when you click to open a new one
                $(this).parent().siblings().each(function() {
                    $panel = $(this).attr("id");

                    if ($(this).children("ul").is(":visible") && $panel != "open") {
                        $(this).children("ul").slideToggle("medium", "easeOutSine");
                    }
                });
        });

        /////////////////////////////////////////////
        // FAQs

        $("#faqs > div > p").hide(); // Close any open faqs

        $("#faqs > div > h2").click(function () {

                $answer = $(this).parent().children("p");

                // Open clicked one
                $answer.slideToggle("medium", "easeOutSine");

                // Loops through each panel and closes any open ones when you click to open a new one
                $answer.parent().siblings().children("p").each(function() {
                    $(this).slideUp();
                });
        });

        /////////////////////////////////////////////
        // Admin Area login

        $('#admin').submit(function() {

            var admindetails = $(this).serialize();
            $('#submitBtn').attr("disabled",true).val('Logging in...');

            $.post('ajax-admin-login.php', admindetails, function(data)
            {
                if(data){

                    if (data.indexOf("Logged")!=-1){
                        window.location.href = "add-entry.html"; return false;
                        /*
                        $('#submitBtn').attr("disabled",true).val('Thank you');
                        $('#logout').fadeIn();
                        $('#errorHolder').fadeOut();
                        $('#admin').slideUp('slow', function(){
                            $('#hiddenForms').slideDown('slow',function(){
                                //$('#errorHolder').html(data).fadeIn('slow');
                            });
                        });
                        */
                    }
                    else{
                        $('#submitBtn').attr("disabled",false).val('Login');
                        $('#errorHolder').html(data).fadeIn('slow');
                    }
                }

            });

            return false;
        });

        /////////////////////////////////////////////
        // Competition entry form

        // validate email entry
        var isValidEmail = false;

        $("#udihur-udihur").keyup(function(){

            var email = $("#udihur-udihur").val();



            if(email != 0)
            {
                if(isValidEmailAddress(email))
                {
                    $("#validEmail").css({
                        "background-image": "url('../img/validYes.png')"
                    });
                    isValidEmail = true;
                } else {
                    $("#validEmail").css({
                        "background-image": "url('../img/validNo.png')"
                    });
                    isValidEmail = false;
                }
            } else {
                $("#validEmail").css({
                    "background-image": "none"
                });
            }

        });

        function isValidEmailAddress(emailAddress) {
             var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
             return pattern.test(emailAddress);
        }


        $('#competitonEntry').submit(function() {

            //get name and email from campaign monitor form and rest of competition entry form
            var details = 'name=' + $('#name').val() + '&email=' + $('#udihur-udihur').val() + '&' + $(this).serialize();
            $('#submitBtn').attr("disabled",true).val('Inserting...');


            // First, disable the form from submitting
            $('form#subForm').submit(function() { return false; });

            // Grab form action
            var formAction = $("#subForm").attr("action");

            // Hack together id for email field
            var id = "udihur";
            var emailId = id + "-" + id;

            var str = $('#subForm').serialize();

            // Add form action to end of serialized data
            var serialized = str + "&action=" + formAction;


            if(isValidEmail)
            {

                $.post('ajax-competition.php', details, function(data)
                {
                    if(data){

                        $('#errorHolder').html(data).fadeIn('slow');

                        if (data.indexOf("successfully")!=-1){

                            // send name and email to campaign monitor newsletter subscriber list
                            // only if they have checked the subscribe box
                            if($("#subscribe").is(":not(':checked')")){
                                jQuery.ajax({
                                   url: "../proxy.html",
                                    type: "POST",
                                    data: serialized,
                                    success: function(html){}
                                });
                            }

                            $('#submitBtn').attr("disabled",true).val('Thank you');

                            $('#errorHolder').delay(7000).slideUp('slow');

                            //clear entry fields
                            $('#competitonEntry').find(':input[type=text]').each(function(){ $(this).val("") });
                            $('#subForm').find(':input[type=text]').each(function(){ $(this).val("") });
                            $('#subscribe').attr("checked", false);
                        }
                        else{
                            $('#submitBtn').attr("disabled",false).val('Send us your question');
                        }
                    }

                });

            }
            else
            {
                var data =
                '<div id="error"><h5>The entry could not be processed because of the following errors:</h5>'+
                '<ul>'+
                '<li>The Email address is empty or invalid</li>'+
                '</ul>'+
                '<p>Please check and try again.</p>'+
                '</div>';

                $('#errorHolder').html(data).fadeIn('slow');
            }


            return false;
        });

        $('#logout').click(function() {

             $.get('ajax-logout.php', function(data) {
              if(data){
                    window.location.href = "index.html"; return false;
                    /*
                    $('#logout').fadeOut();
                    $('#admin').find('input:not([type=submit])').each(function(){ $(this).val("") });
                    $('#hiddenForms').slideUp('slow', function(){
                        $('#admin').slideDown('slow');
                    });
                    */
              }
            });

            return false;
        });


        /////////////////////////////////////////////
        // Contact us form
        $('#errorHolder').hide();

        $('#contact').submit(function() {

            //get name and email from campaign monitor form and rest of entry form
            var details = 'name=' + $('#name').val() + '&email=' + $('#udihur-udihur').val() + '&' + $(this).serialize();

            $('#submitBtn').attr("disabled",true).val('Sending...');


            // First, disable the form from submitting
            $('form#subForm').submit(function() { return false; });

            // Grab form action
            var formAction = $("#subForm").attr("action");

            // Hack together id for email field
            var id = "udihur";
            var emailId = id + "-" + id;

            var str = $('#subForm').serialize();

            // Add form action to end of serialized data
            var serialized = str + "&action=" + formAction;


            // only begin process if the email address is valid
            if(isValidEmail)
            {

                $.post('ajax-contact.php', details, function(data)
                {
                    if(data){

                        // user feedback
                        $('#errorHolder').html(data).fadeIn('slow');

                        // change submit button state depending on success
                        if (data.indexOf("successfully")!=-1){

                            // send name and email to campaign monitor newsletter subscriber list
                            // only if they have checked the subscribe box
                            if($('#subscribe').is(':checked')){
                                $.ajax({
                                   url: "proxy.html",
                                    type: "POST",
                                    data: serialized,
                                    success: function(html){}
                                });
                            }

                            $('#submitBtn').attr("disabled",true).val('Thank you');
                        }
                        else{
                            $('#submitBtn').attr("disabled",false).val('Send us your question');
                        }

                    }

                });

            }
            else
            {
                $('#submitBtn').attr("disabled",false).val('Send us your question');

                var data =
                '<div id="error"><h5>The entry could not be processed because of the following errors:</h5>'+
                '<ul>'+
                '<li>The Email address is empty or invalid</li>'+
                '</ul>'+
                '<p>Please check and try again.</p>'+
                '</div>';

                $('#errorHolder').html(data).fadeIn('slow');
            }


            return false;
        });


});


function showCompForm(){
    $('#admin').hide();
    $('#logout').show();
    $('#hiddenForms').show();
};
