window.onload = init;

//IE 6 DevNote
function init() {
    window.step1Button = document.forms[0].step1Button
    window.step2Button = document.forms[0].step2Button;
    window.submitButton = document.forms[0].submitButton;
    window.goButton = document.forms[0].goButton;


}



function Home_Init() {
    var searchDefaultText = "Enter softy name";

    $(document).ready(function() {
        GallerySearch_Init();

        $("div.top-buttons .search #search_box").focus(function() {
            if ($(this).val() == searchDefaultText)
                $(this).val("");
        });

        $("div.top-buttons .search #search_box").blur(function() {
            if ($(this).val() == "")
                $(this).val(searchDefaultText);
        });

        $("div.top-buttons .search img").click(function() {
            //perform search
        });

        $("div.top-buttons .search #search_box").keyup(function(e) {
            if (e.keyCode == 13) {
                //perform search
            }
        });

        $("div.top-buttons div.gallery a").click(function() {
            //gallery
        });

        var flashvars_step1 = { 'js': 'EnterStep1()' };
        var flashvars_step2 = { 'js': 'EnterStep2()' };


        swfobject.embedSWF("img/flash/ContentHeader.swf", "softy-header", "520", "320", "9.0.0", "expressInstall.swf", flashvars, params, attributes_header);
        swfobject.embedSWF("img/flash/ClickHereToEnter_Button.swf", "step1-clickhere", "70", "70", "9.0.0", "expressInstall.swf", flashvars_step1, params, attributes_step1);
        swfobject.embedSWF("img/flash/ClickHereToEnter_Button.swf", "step2-clickhere", "70", "70", "9.0.0", "expressInstall.swf", flashvars_step2, params, attributes_step2);



    });
}

function parseXml(xml) {
    if (jQuery.browser.msie) {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(xml);
        xml = xmlDoc;
    }
    return xml;
} 



function Step1_Init() {
    $(document).ready(function() {
        flashvars = { 'js': 'FormSubmit()' };
        flashvars_proceed = { 'js': 'EnterStep2(' + $("span.uniquecode").text() + ')' };

        swfobject.embedSWF("img/flash/ContentHeader.swf", "softy-header", "520", "320", "9.0.0", "expressInstall.swf", flashvars, params, attributes_header);
        swfobject.embedSWF("img/flash/submit_button.swf", "step1-submit", "70", "70", "9.0.0", "expressInstall.swf", flashvars, params, attributes_submit);

        $("div.form-wrapper input, input.barcode").focus(function() {
            var defaultText = $(this).attr("rel");

            if ($(this).val() == defaultText)
                $(this).val("");
        });

        $("div.form-wrapper input, input.barcode").each(function() {
            if ($(this).val() == "")
                $(this).val($(this).attr("rel"));
        });

        $("div.form-wrapper input, input.barcode").blur(function() {
            var defaultText = $(this).attr("rel");
            if ($(this).val() == "")
                $(this).val(defaultText);
        });

        $.validator.addMethod("required-default", function(value, element) {
            return (value.length > 0 && value != $(element).attr("rel"));
        }, "");

        //jQuery.validator.messages.required = "";


        $("form").validate({
            rules: {
                phone: {
                    required: true,
                    minlength: 8,
                    maxlength: 10
                }
            },
            messages: {
                phone: {
                    required: "Phone Number is a mandatory field",
                    minlength: "Phone Number requires a minimum 8 digits",
                    maxlength: "Phone Number requires a maximum of 10 digits"
                }
            },

            highlight: function(element, errorClass) {
                var name = $(element).attr("name");

                if (name == "terms" || name == "permission" || name == "agreecontact")
                    $(element).next().css("color", "red");
                else
                    $(element).addClass("error");
            },

            unhighlight: function(element, errorClass) {
                var name = $(element).attr("name");

                if (name == "terms" || name == "permission" || name == "agreecontact")
                    $(element).next().css("color", "#fff");
                else
                    $(element).removeClass("error");
            },
            errorContainer: 'div.step1-box-errors',
            errorLabelContainer: '#error-box',
            wrapper: 'label',
            errorElement: 'span',

            errorPlacement: function(error, element) {
                if ($(element).attr("class").indexOf("required-default") > -1) {
                    $(error).text($(element).attr("rel").substring(0, $(element).attr("rel").length - 1) + " is a mandatory field");
                }

                //$("div.step1-box-errors div.error-box").append(error);
                //$("div.step1-box-errors").show();
            },

            submitHandler: function(form) {
                //submit to proxy via AJAX, parse response (check 'Status')
                var postdata = $("form").serialize();
                postdata += "&sub=true";
                $.ajax({
                    type: 'GET',
                    //type: 'POST',
                    //url: 'Services/Step1.ashx?' + postdata,
                    url: 'Step1.aspx?' + postdata,
                    success: function(xml) {
                        var msg = parseXml(xml);
                        //check status node for success
                        var status = $(msg).find('Status').text();

                        if (status == 'Valid') {

                            var uniqueCode = $(msg).find("UniqueCode").text();
                            $("span.uniquecode").text(uniqueCode);

                            //save details to db
                            //var fname = $("input.firstname").val();
                            //var lname = $("input.lastname").val();
                            //var address = $("input.address").val();
                            //var state = $("input.state").val();
                            //var postcode = $("input.postcode").val();
                            //var phone = $("input.phone").val();
                            //var email = $("input.email").val();

                            //$.get('Services/SaveUser.ashx', { 'u': uniqueCode, 'fname': fname, 'lname': lname, 'address': address, 'state': state, 'postcode': postcode, 'phone': phone, 'email': email }, function(data) {

                            //});

                            //set cookie with unique code & user data for next step
                            $.cookie("step1_success", $("form").serialize(), { expires: 300 });

                            $("div.step1-wrapper").hide();
                            $("div.step1-thanks").show();
                        }
                        else {
                            if (status == 'ExceedMaxEntries') {
                                //todo: handle this error
                                var errorHtml = "<label class='error'><span>Error: You have exceeded the limit of 5 entries per day.<br />This entry was not valid but you can enter again every day until 10th April 2010. Keep buying your specially marked packs of Tip Top® Sunblest® bread and good luck!</span></label>";
                            }
                            else {
                                //invalid status
                                var errorHtml = "<label class='error'><span>Error: The barcode you have submitted is incorrect.</span><br />Please check your barcode and try again.</label>";
                            }

                            $("div#error-box").append(errorHtml);
                            $("div.step1-box-errors").show();
                            $("div#error-box").show();

                        }
                    }
                });
            }
        });

        swfobject.embedSWF("img/flash/Step2_Button.swf", "thanks-proceed", "70", "70", "9.0.0", "expressInstall.swf", flashvars_proceed, params, attributes_step2);
    });

}

function Step2_Init() {
    $(document).ready(function() {
        $("form").attr("enctype", "multipart/form-data");

        var flashvars = { 'js': 'FormSubmit()' };
        var flashvarsGo = { 'js': 'Step2_Go()' };

        swfobject.embedSWF("img/flash/ContentHeader.swf", "softy-header", "520", "320", "9.0.0", "expressInstall.swf", flashvars, params, attributes_header);
        swfobject.embedSWF("img/flash/submit_button.swf", "step2-submit", "70", "70", "9.0.0", "expressInstall.swf", flashvars, params, attributes_submit);
        swfobject.embedSWF("img/flash/Go_Button.swf", "go_btn", "40", "40", "9.0.0", "expressInstall.swf", flashvarsGo, params, attributes_go);
        GallerySearch_Init();

        var cookieData = $.cookie("step1_success");
        var qs = new Querystring(cookieData);
        var qs2 = new Querystring();

        var uniquecode = qs2.get("u");
        var firstname = qs.get("firstname");
        var lastname = qs.get("lastname");
        var address = qs.get("address");
        var state = qs.get("state");
        var postcode = qs.get("postcode");
        var phone = qs.get("phone");
        var email = qs.get("email");

        if (uniquecode && uniquecode != "") {
            $("input#uniquecode").val(uniquecode);
        }
        if (firstname && firstname != "") {
            $("input#firstname").val(firstname);
        }
        if (lastname && lastname != "") {
            $("input#lastname").val(lastname);
        }
        if (address && address != "") {
            $("input#address").val(address);
        }
        if (state && state != "") {
            $("select#state").val(state);
        }
        if (postcode && postcode != "") {
            $("input#postcode").val(postcode);
        }
        if (phone && phone != "") {
            $("input#phone").val(phone);
        }
        if (email && email != "") {
            $("input#email").val(email);
        }

        $("div.form-wrapper input, input.uniquecode").focus(function() {
            var defaultText = $(this).attr("rel");

            if ($(this).val() == defaultText)
                $(this).val("");
        });

        $("div.form-wrapper input, input.uniquecode").each(function() {
            if ($(this).val() == "")
                $(this).val($(this).attr("rel"));
        });

        $("div.form-wrapper input, input.uniquecode").blur(function() {
            var defaultText = $(this).attr("rel");
            if ($(this).val() == "")
                $(this).val(defaultText);
        });

        $("textarea").keyup(function() {
            var max = 255;
            if ($(this).val().length > max) {
                $(this).val($(this).val().substr(0, max));
            }
        });

        $.validator.addMethod("required-default", function(value, element) {
            return (value.length > 0 && value != $(element).attr("rel"));
        }, "");

        //jQuery.validator.messages.required = "";

        $("form").validate({
            //errorPlacement: function(error, element) {
            // if ($(element).attr("class").indexOf("required-default") > -1) {
            //     $(error).text($(element).attr("rel") + " is a mandatory field");
            // }

            //    $("div.step1-box-errors div.error-box").append(error);
            //    $("div.step1-box-errors").show();
        // }

            rules: {
                nominatorContactNumber: {
                    required: true,
                    minlength: 8,
                    maxlength: 10
                },
                nomineeContactNumber: {
                    required: true,
                    minlength: 8,
                    maxlength: 10
                }
            },
            messages: {
                nominatorContactNumber: {
                    required: "Nominators Phone Number is a mandatory field",
                    minlength: "Nominators Phone Number requires a minimum 8 digits",
                    maxlength: "Nominators Phone Number requires a maximum of 10 digits"
                },
                nomineeContactNumber: {
                    required: "Nominees Phone Number is a mandatory field",
                    minlength: "NomineesPhone Number requires a minimum 8 digits",
                    maxlength: "NomineesPhone Number requires a maximum of 10 digits"
                }
            },
            
            
            
            highlight: function(element, errorClass) {
                var name = $(element).attr("name");

                if (name == "terms" || name == "permission" || name == "agreecontact")
                    $(element).next().css("color", "red");
                else
                    $(element).addClass("error");
            },

            unhighlight: function(element, errorClass) {
                var name = $(element).attr("name");

                if (name == "terms" || name == "permission" || name == "agreecontact")
                    $(element).next().css("color", "#fff");
                else
                    $(element).removeClass("error");
            },
            errorContainer: 'div.step2-box-errors',
            errorLabelContainer: '#error-box',
            wrapper: 'label',
            errorElement: 'span',
            submitHandler: function(form) {
                //todo: submit to proxy via AJAX, parse response (check 'Status')
                document.forms[0].submit();
            }
        });

        $("a#uniquecode-error").fancybox({ 'autoDimensions': false, 'width': 325, 'padding': '0', 'centerOnScroll': true, 'overlayOpacity': 0.6 });
        //$("a#uniquecode-error").click();
    });
}

function Gallery_Init() {
    $(document).ready(function() {
        var pageIndex = 1;
        var numPerPage = 8;
        var totalCount = 0;
        var currentPage = 0
        var firstName, lastName, n, pageIndex;
        var maxPages;
        var back = $("div.gallery-wrapper div.pagination a.back")
        var next = $("div.gallery-wrapper div.pagination a.next")



        var hasChanged = false;

        firstName = $.jqURL.get('f');
        lastName = $.jqURL.get('l');
        pageIndex = $.jqURL.get('i') == undefined ? 1 : $.jqURL.get('i');

        $("div.search-box input").eq(0).val(firstName);
        $("div.search-box input").eq(1).val(lastName);

        $("div.search-box input").change(function() {
            pageIndex = 1;
        });

        $("div.search-box input").each(function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr("rel"));
            }
        });

        $("div.search-box input").focus(function() {
            if ($(this).val() == $(this).attr("rel")) {
                $(this).val('');
            }
        });

        $("div.search-box input").blur(function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr("rel"));
            }
        });


        flashvars = { 'js': 'ClickToEnter()' };
        swfobject.embedSWF("img/flash/ContentHeaderWithButton.swf", "softy-header-alt", "520", "260", "9.0.0", "expressInstall.swf", flashvars, params, attributes_header);


        $(back).click(function() {
            pageIndex = Math.max(1, pageIndex - numPerPage);
            $("div.search-box a.search-btn").click();
        });




        $(next).click(function() {
            maxPages = Math.ceil(totalCount / numPerPage);
            if (pageIndex + numPerPage <= totalCount) {
                pageIndex += numPerPage;
                $("div.search-box a.search-btn").click();
            }
        });

        $("div.search-box").keyup(function(e) {
            //alert(e.keyCode);
            if (e.keyCode == 13) {
                $("div.search-box a.search-btn").click();
            }
        });
        


        $("div.search-box a.search-btn").click(function() {
 
            //determine first name, last name
            firstName = $(".search-fname").val();
            lastName = $(".search-lname").val();

            if (firstName == $(".search-fname").attr("rel"))
                firstName = "";
            if (lastName == $(".search-lname").attr("rel"))
                lastName = "";

                

            //hit web service, get all that match search string
            PerformImageSearch(firstName, lastName, pageIndex, function(msg) {
                //check status node for success
                var status = $(msg).find('Status').text();
                totalCount = Math.abs($(msg).find('TotalCount').text());


                if (pageIndex == 1) {
                    $(back).css({ "visibility": "hidden" });
                } else {
                    $(back).css({ "visibility": "visible" });
                }

                //alert((pageIndex + numPerPage) + " || " + totalCount + " || " + maxPages)
                if ((pageIndex + numPerPage) > totalCount) {
                    $(next).css({ "visibility": "hidden" });
                } else {
                    $(next).css({ "visibility": "visible" });
                }




                //empty container
                $("div#gallery-items").empty();

                if (status == 'Valid') {
                    $("div.gallery-wrapper div.searchError").hide();
                    $("div.pagination").show();

                    //populate container
                    $(msg).find("ImageItem").each(function() {
                        var imageId = $(this).find("ImageID").text();
                        var fname = $(this).find("FirstName").text();
                        var lname = $(this).find("LastName").text();
                        var thumbnail = $(this).find("ThumbnailImage").text();

                        var htmlText = "<div class='item'><div class='image'><a class='gallery-item' href='Profile.aspx?i=" + imageId + "'><img src='" + thumbnail + "' border='0' /></a></div><div class='name'>" + fname + "<br />" + lname + "</div></div>";

                        $("div#gallery-items").append(htmlText);

                    });

                    if (firstName != '' || lastName != '')
                        $("div.gallery-wrapper h2").text("Gallery Search Results");
                    else
                        $("div.gallery-wrapper h2").text("Gallery");
                }
                else {
                    ShowGalleryError($(msg).find('Text').text());
                }
            });

            return false;
        });

        $("div.search-box a.search-btn").click();
    });

}

function Profile_Init() {
    $(document).ready(function() {
        GallerySearch_Init();

        flashvars = { 'js': 'ClickToEnter()' };
        swfobject.embedSWF("img/flash/ContentHeaderWithButton.swf", "softy-header-alt", "520", "260", "9.0.0", "expressInstall.swf", flashvars, params, attributes_header);

        $("div.search-box a.search-btn").click(function() {
            var firstName = $(this).prev().prev().val();
            var lastName = $(this).prev().val();

            if (firstName || lastName)
                window.location = "Gallery.aspx?f=" + firstName + "&l=" + lastName;

            return false;
        });

    });
}

function GallerySearch_Init() {
    $("div.top-buttons div.search input").each(function() {
        if ($(this).val() == '') {
            $(this).val($(this).attr("rel"));
        }
    });

    $("div.top-buttons div.search input").focus(function() {
        if ($(this).val() == $(this).attr("rel")) {
            $(this).val('');
        }
    });

    $("div.top-buttons div.search input").blur(function() {
        if ($(this).val() == '') {
            $(this).val($(this).attr("rel"));
        }
    });


    $('div.search').keyup(function(e) {
        //alert(e.keyCode);
        if (e.keyCode == 13) {
            $("div.top-buttons div.search").click();
        }
    });
    
    

    $("div.top-buttons div.search img").click(function() {

        var fname = $(".search_fname").val();
        var lname = $("#search_lname").val();

        var fname_defaultText = $(".search_fname").attr("rel");
        var lname_defaultText = $("#search_lname").attr("rel");

        if (fname == fname_defaultText) fname = ''; 
        if (lname == lname_defaultText) lname = '';

        if (fname != '' || lname != '') {
            window.location = "Gallery.aspx?f=" + fname + "&l=" + lname;
        }
    });
}

function Content_Init() {
    $(document).ready(function() {
        flashvars = { 'js': 'ClickToEnter()' };
        swfobject.embedSWF("img/flash/ContentHeaderWithButton.swf", "softy-header-alt", "520", "260", "9.0.0", "expressInstall.swf", flashvars, params, attributes_header);

        $("#softy-container").css("float", "left");
    });
}

function ClickToEnter() {
    window.location = 'Default.aspx';
}

function EnterStep1() {
    window.location = 'Step1.aspx';
}

function EnterStep2() {
    var uniqueCode = $("span.uniquecode").text();

    if (uniqueCode && uniqueCode != '')
        window.location = 'Step2.aspx?u=' + uniqueCode;
    else
        window.location = 'Step2.aspx';
}

function ShowGalleryError(errorText) {
    var errorObject = $("div.gallery-wrapper div.searchError");
    $(errorObject).text(errorText);
    $("div.pagination").hide();
    $(errorObject).show();
}

function FormSubmit() {
    $("#error-box").hide();
    $("form").submit();
}

function PerformImageSearch(firstName, lastName, Index, callback) {
    //if there is no callback supplied it is pointless to make the request
    if (callback) {
        $.ajax({
            type: 'POST',
            url: 'Services/Search.aspx',
            data: { firstname: firstName, lastname: lastName, index: Index, images: 8 },
            success: function(msg) { callback(msg); }
        });
    }
}

function Step2_Go() {
    var uniquecode = $("div.code-container input").val();

    if (uniquecode && uniquecode != '')
        window.location = 'Step2.aspx?u=' + uniquecode;
}