/* ----------------------------------------------------------------------------------------- 
____________________________________________________________________

Author - Tony Skurat
____________________________________________________________________

----------------------------------------------------------------------------------------- */
// when the DOM is ready...(initialization)
// ------ You can make all your customizations here. ---------- \\
"use strict";
$(document).ready(function () {
    // login form
    var wrapperId = "#wrapper",  // main container
        waitId = "#wait",  // wait message container
        formId = "#login-form",  // submit button identifier
        userId = "#u",  // user input identifier
        passId = "#p",  // password input identifier
        confirmId = "#c",  // confirm password input identifier
		announcementId = "#announce", //announcements container
        waitNote = "Loading...",  // loading message
        jsErrMsg = "<span class=\"warning\"><b>*Your username or password is not valid.</b></span>",  // clientside error message
        jsErrMsg1 = "<span class=\"warning\"><b>*Your password must be at least eight characters long.</b></span>",  // clientside error message
        jsErrMsg2 = "<span class=\"warning\"><b>*Your passwords do not match.</b></span>",  // clientside error message
        postFile = "php/login.post.php",  // post handler
        changeFile = "php/login.change.php",  // post handler
		announcementFile = "php/login.announcements.php",  // post handler
        _u, _p, _c, nameValue, subjectValue, emailValue, messageValue, emailReg, correct;
                      
    $(waitId).hide();  // hide first
    initForm();  // init form function	
	
    function initForm() {
        // get request to load form
        $.getJSON(postFile, function (data) {
            if (data.status === true) {				
                $(waitId).fadeOut("slow", function () {
                    $(wrapperId).fadeOut("slow", function () {
                        $(this).html(data.message).fadeIn();
                        $("a#changeP").click(function () {
                            $(wrapperId).html(data.message).fadeOut();
                            initPassForm();
                            return false;
                        });
						$("a#announcements").click(function () {			
                            $(".section").slideUp(500);
							setTimeout(function () {
								$(announcementId).load(announcementFile);
								setTimeout(function () {
                                   $("#announcement").slideDown(800);	
								}, 175);							           
                            }, 500);
                            return false;
                        });
                    });
                }).html();				
            } else {
                // show form
                $(wrapperId).html(data.message).fadeIn("slow", function () {
                    // hide message
                    $(waitId).fadeOut("fast", function () {
                        // submit handler
                        $(formId).submit(function () {
                            _u = $(userId).val(); // form user
                            _p = $(passId).val(); // form id
                            //@ valid user ( modify as needed )
                            if (_u.length < 4) {
                                $(waitId).html(jsErrMsg).fadeIn("fast", function () {
                                    $(userId).focus();
                                });
                            } else {
                                //@ valid password ( modify as needed )
                                if (_p.length < 4) {
                                    $(waitId).html(jsErrMsg).fadeIn("fast", function () {
                                        $(passId).focus();
                                    });
                                } else {
                                    $.post(postFile, {
                                        u: _u,
                                        p: _p
                                    }, function (data) {
                                        if (data.status === true) {	
                                                window.location = data.url;                                           
                                        } else {
                                            $(waitId).html(data.message).fadeIn("fast", function () {
                                                $(userId).focus();
                                            });
                                        }
                                    }, "json");
                                }
                            }
                            return false;
                        });
                        $(userId).focus();
                    }).html();
                });
            }
        });
    }
	
    function initPassForm() {
        // get request to load form
        $.getJSON(changeFile, function (data) {
            // show form			
            setTimeout(function () {
                $(wrapperId).html(data.message).fadeIn("slow", function () {
                    // back handler												 
                    $("input#back").click(function () {
                        initForm();
                        return false;
                    }); // submit handler
                    $(formId).submit(function () {
                        _p = $(passId).val(); // form id
                        _c = $(confirmId).val(); // confirm id
                        //@ valid password( modify as needed )
                        if (_p.length < 8) {
                            $(waitId).html(jsErrMsg1).fadeIn("fast", function () {
                                $(passId).focus();
                            });
                        } else {
                            //@ valid password ( modify as needed )
                            if (_c.length < 8) {
                                $(waitId).html(jsErrMsg1).fadeIn("fast", function () {
                                    $(confirmId).focus();
                                });
                            } else {
                                if (_c !== _p) {
                                    $(waitId).html(jsErrMsg2).fadeIn("fast", function () {
                                        $(passId).focus();
                                    });
                                } else {
                                    $.post(changeFile, {
                                        p: _p,
                                        c: _c
                                    }, function (data) {
                                        $(waitId).fadeOut("slow", function () {
                                            $(wrapperId).fadeOut("slow", function () {
                                                $(this).html(data.message).fadeIn();
                                                $("a#back").click(function () {
                                                    initForm();
                                                    return false;
                                                });
                                            });
                                        });
                                    }, "json");
                                }
                            }
                        }
                        return false;
                    });
                    $(passId).focus();
                });
            }, 175);
        });
		
		
    }	
    // ------ This function is used to open links in external window/tab without relying on the deprecated target attribute. So, whenever you want to open links in a new window. just add class="external"
    $("a.external").click(function () {
        return !window.open($(this).attr("href"));
    }); // ------ This function selects the current nav and adds a class of "active"
	
    function selectNav() {
        $(this).parents("#mainNav:first").find("a").removeClass("active").end().end().addClass("active");
    }
    $("#mainNav").find("a").click(selectNav); // go find the navigation link that has this target and select the nav

    function trigger(data) {
        var el = $("#mainNav").find('a[href$="' + data.id + '"]').get(0);
        selectNav.call(el);
    }
    if (window.location.hash) {
        trigger({
            id: window.location.hash.substr(1)
        });
    } else {
        $("#mainNav a:first").click();
    }
    $("#mainNav li a").click(function () {
        $(this).siblings().removeClass("active"); // Unset all other buttons			
        $(this).addClass("active");

        $(".section").slideUp(500); // Slide up content
        var content_show = $(this).attr("href");
        setTimeout(function () {
			$("#contentWrapper").height("auto");
            $(content_show).slideDown(800);
        }, 500);
        return false;
    });
    $(".piped li a").click(function () {			
        $(".section").slideUp(500);
        var content_show = $(this).attr("href");
        setTimeout(function () {
            $(content_show).slideDown(800);
        }, 500);
        return false;
    });
    // Gallery Fade	
    $(".latest_img").fadeTo("slow", 0.85); // This sets the opacity of the thumbs to fade down to 85% when the page loads
    $(".latest_img").hover(function () {
        $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    }, function () {
        $(this).fadeTo("slow", 0.85); // This should set the opacity back to 85% on mouseout
    });
    // Fancybox - Gallery	
    $("#iframe").fancybox({
        'padding': 0,
        'width': 677,
        'height': 485,
        'autoScale': true,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'type': 'iframe'
    });
    $(".image").fancybox({
        'padding': 5,
        'titleShow': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic'
    });
    $("#map").fancybox({
        'padding': 5,
        'titleShow': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'type': 'iframe'
    });
    // Form Validate
    var options = {
        beforeSubmit: validate,         
        success: showResponse,        
        //clearForm: true, // clear all form fields after successful submit 
        resetForm: true // reset the form after successful submit 
    }; // bind form using 'ajaxForm' 
    $("#contact-form").ajaxForm(options);
	
    // Contact Form settings
    function showResponse() {
        $('input.send').animate({
            opacity: "hide"
        }, "fast");
        setTimeout(function () {
            $('#success').animate({
                opacity: "show"
            }, "slow");
        }, 500);
        setTimeout(function () {
            $('#success').animate({
                opacity: "hide"
            }, "fast");
            setTimeout(function () {
                $('input.send').animate({
                    opacity: "show"
                }, "slow");
            }, 500);
        }, 5000);

    }
    function validate(formData, jqForm, options) {		
        $("li.error").animate({
            opacity: "hide"
        }, "slow");
        nameValue = $('input[name=name]').fieldValue();
        subjectValue = $('input[name=subject]').fieldValue();
        emailValue = $('input[name=email]').fieldValue();
        messageValue = $('textarea[name=message]').fieldValue();
        emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        correct = true;
        if (!nameValue[0]) {
            $("li.error.wrong_name").animate({
                opacity: "show"
            }, "slow");
            correct = false;
        }
        if (!emailValue[0]) {
            $("li.error.wrong_email").animate({
                opacity: "show"
            }, "slow");
            correct = false;
        } else if (!emailReg.test(emailValue[0])) {
            $("li.error.wrong_email").animate({
                opacity: "show"
            }, "slow");
            correct = false;
        }
        if (!messageValue[0]) {
            $("li.error.wrong_message").animate({
                opacity: "show"
            }, "slow");
            correct = false;
        }
        if (!subjectValue[0]) {
            $("li.error.wrong_subject").animate({
                opacity: "show"
            }, "slow");
            correct = false;
        }
        if (!correct) {
            return false;
        }
    }
    $("p#success").click(function () {
        $(this).animate({
            opacity: "hide"
        }, "slow");
    });
});
