﻿
// Check that the page has loaded
$(document).ready(function() {

    // Preload menu images 
    menuTopImage = new Image();
    menuTopImage.src = "/designerplants/i/dropDown_top.png";
    menuMiddleImage = new Image();
    menuMiddleImage.src = "/designerplants/i/dropDown_middle.png";
    menuMiddleOverImage = new Image();
    menuMiddleOverImage.src = "/designerplants/i/dropDown_middle_over.png";
    menuBottomImage = new Image();
    menuBottomImage.src = "/designerplants/i/dropDown_bottom.png";

    // MAIN NAV DROPDOWN  
    $('#mainNav LI A').hover(
        function() {
            // Show dropdown
            $(this).parent('LI').find('.dropdown').show();
        },

        function() {
            // Hide dropdown
            $(this).parent('LI').find('.dropdown').hide();
        });

    $('#mainNav .dropdown').hover(
        function() {
            // Show dropdown
            $(this).show();
        },

        function() {
            // Hide dropdown
            $(this).hide();
        });

    // Item rollover
    $('#mainNav .dropdown .item').hover(
        function() {
            if (!$('BODY').hasClass('browserIE6')) {
                $(this).css({ backgroundImage: 'url(i/dropDown_middle_over.png)' });
            } else {
                $(this).css({ backgroundImage: 'url(i/dropDown_middle_over.gif)' });
            }
        },

        function() {
            if (!$('BODY').hasClass('browserIE6')) {
                $(this).css({ backgroundImage: 'url(i/dropDown_middle.png)' });
            } else {
                $(this).css({ backgroundImage: 'url(i/dropDown_middle.gif)' });
            }
        }
    );

    // case study link
    $('a.caseStudies, a.information').click(function() {
        return false;
    });

    // Big target item
    $("#mainNav .dropdown .item A").bigTarget({
        clickZone: '.item' // jQuery parent selector
    });
    $('.item').css({ 'cursor': 'pointer' });


    // CASE STUDY GALLERY

    // Remove margin for last Thumbnail
    $('.caseStudyGallery .thumbnails .thumbnail:last').css({ margin: '0' });

    // Load correct image on click
    $('.caseStudyGallery .thumbnails .thumbnail A').click(function() {
        var imgURL = $(this).attr('href');
        var img = new Image();
        $('.caseStudyGallery .thumbnails .thumbnail A .overlay').remove();
        $(this).append('<span class="overlay"></span>');
        $(img).load(function() {

            $('.caseStudyGallery .mainImg IMG').attr('src', imgURL);


            Reflection.remove(document.getElementById("studyImage"));
            Reflection.add(document.getElementById("studyImage"));
        }).attr('src', imgURL);

        return false;

    });

    // Add reflection to page load if on case studies 
    if (window.location.toString().indexOf("caseStudy") > 0) {
        $('body').attr('OnLoad', "Reflection.add(document.getElementById('studyImage'))");
    }

    // Select the first image
    $('.caseStudyGallery .thumbnails .thumbnail A:first').append('<span class="overlay"></span>');
    $('.caseStudyGallery .mainImg IMG').attr('id', 'studyImage');

    // Quote marks for testimonials  
    $('.quote').prepend('<img src="i/testimonials/quote_left.gif" />');
    $('.quote').append('<img src="i/testimonials/quote_right.gif" />');


    // TRADE LOGIN
    $('#mainNav LI .tradeLogin.loggedOut').click(function() {
        $('#tradeLogin').show();
    });

    if (document.location.search.indexOf("login=true") > 0) {
        $('#tradeLogin').show();
    }

    $('.cancel a').click(function() {
        $('#tradeLogin').hide();
        return false;
    });
    
      // Logout
    $('.logOut A').live('click', function() {
        $.ajax({
            type: "POST",
            url: '/designerplants/methods/methods.aspx/logOut',
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                window.location = "/designerplants/";
            }

        });

        return false;

    });
    
    // Forgot password
    $('.forgotPassword A').live('click', function() {
          if ($('#txt_loginEmail').val() == "") {
            $('#loginError').html("<span class=\"error\">Please enter your email address</span>");
        }
        else if (!isValidEmail($('#txt_loginEmail').val())) {
            $('#loginError').html("<span class=\"error\">Please enter a valid email address</span>");
        }
        else {
            $.ajax({
                type: "POST",
                url: 'methods/methods.aspx/passwordReminder',
                data: "{'email': '" + $('#txt_loginEmail').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    result = JSON.parse(data.d);
                    if (result.success) {
                        $('#loginError').html('Successfully sent reminder');
                    }
                    else {
                        if (result.errorMessage != "Server Error") {
                            $('#loginError').html("<span class=\"error\">" + result.errorMessage + "</span>");
                        }
                        else {
                            $('#loginError').html("<span class=\"error\">There was an error, please try again later</span>");
                        }
                    }
                }
            });
        }
        return false;
    });

    // TRADE CAT NAVIGATION/SKINNING    
    $('#tradeCatNav LI A').click(function() {
        $('.loading').show();
        // Nav colouring
        $('#tradeCatNav LI').removeClass('selected');
        $(this).parent('LI').addClass('selected');

        // Body skinning
        var skin = $(this).attr('class');
        $('#tradeCatSkin').removeClass().addClass(skin);

        $('#plants').empty();
        var letter = $('.index li.selected a').html();
        var category = $(this).attr('title');
        var JSONData = "{'letter': '" + letter + "', 'category': '" + category + "', 'page' : '1'}";
        $.ajax({
            type: "POST",
            url: '/designerplants/tradeCat.aspx/returnPlants',
            data: JSONData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                data = JSON.parse(data.d);
                if (data.plantCount > 1) {
                    // Setup paging
                    $('.pageFrom').html('1');
                    $('.pageTo').html(data.pages);
                    $('.prev').hide();
                    if (data.pages > 1) {
                        $('.next').show();
                    }
                    else {
                        $('.next').hide();
                    }
                    // Render the plants
                    $('#plants').html(data.plants);
                    setDropdowns();
                }
                else {
                    $('#plants').html("<p>No Plants Found In This Category/Letter</p>");
                }
                $('.loading').hide();

            }

        });

        return false;

    });

    var page = parseInt($('.pageTo').html());
    if (page > 1) {
        $('.next').show();
    }

    // Get initial basket status
    $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/getBasket',
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    if (data.d > 0) {
                        $('#basketItems').html(data.d);
                        $('#basket').show();
                    }
                }

     });

    // TRADE CAT LETTER CLICKS    
    $('.index li a').click(function() {
        $('.loading').show();
        if ($(this).parent().hasClass('paging')) {
            page = parseInt($('.pageFrom').html());
            if ($(this).hasClass('prev')) {
                page--;
            }
            else if ($(this).hasClass('next')) {
                page++;
            }
            $('#plants').empty();
            var letter = $('.index li.selected a').html();
            var category = $('#tradeCatNav li.selected a').attr('title');
            var JSONData = "{'letter': '" + letter + "', 'category': '" + category + "', 'page' : '" + page + "'}";
            $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/returnPlants',
                data: JSONData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    data = JSON.parse(data.d);
                    if (data.plantCount > 1) {
                        // Setup paging
                        $('.pageFrom').html(page);
                        $('.pageTo').html(data.pages);
                        if (page > 1) {
                            $('.prev').show();
                        }
                        else {
                            $('.prev').hide();
                        }
                        if (data.pages > 1 && page < data.pages) {
                            $('.next').show();
                        }
                        else {
                            $('.next').hide();
                        }
                        // Render the plants
                        $('#plants').html(data.plants);
                        setDropdowns();
                    }
                    else {
                        $('#plants').html("<p>No Plants Found In This Category/Letter</p>");
                    }
                    $('.loading').hide();
                }

            });
        }
        else {
            $('.index li').removeClass('selected');
            $(this).parent().addClass('selected');

            $('#plants').empty();
            var letter = $('.index li.selected a').html();
            var category = $('#tradeCatNav li.selected a').attr('title');
            var JSONData = "{'letter': '" + letter + "', 'category': '" + category + "', 'page' : '1'}";
            $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/returnPlants',
                data: JSONData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    data = JSON.parse(data.d);
                    if (data.plantCount > 1) {
                        // Setup paging
                        $('.pageFrom').html('1');
                        $('.pageTo').html(data.pages);
                        $('.prev').hide();
                        if (data.pages > 1) {
                            $('.next').show();
                        }
                        else {
                            $('.next').hide();
                        }
                        // Render the plants
                        $('#plants').html(data.plants);
                        setDropdowns();
                    }
                    else {
                        $('#plants').html("<p>No Plants Found In This Category/Letter</p>");
                    }
                    $('.loading').hide();
                }

            });
        }
        return false;
    });

    setDropdowns();

    // Add to basket
    $('.addButton A').live('click', function() {
        var that = $(this);
        var name = $(this).parents('.row').find('.name').html();
        var size = $(this).parents('.row').find('.size').val();
        var form = $(this).parents('.row').find('.form').val();
        var sec_form = $(this).parents('.row').find('.sec_form').val();
        var quantity = $(this).parents('.row').find('input').val();
        if (size == "Size") {
            $(this).parents('.row').find('.addStatus').html("please select a size").show();
        }
        else if (form == "Form" && $(this).parents('.row').find('.form option').length > 1) {
            $(this).parents('.row').find('.addStatus').html("please select a form").show();
        }
        else if (sec_form == "Secondary Form") {
            $(this).parents('.row').find('.addStatus').html("please select a secondary form").show();
        }
        else {
            if (form == "Form") {
                form = "";
            }
            var JSONData = "{'plantName': '" + name + "', 'size': '" + size + "', 'form' : '" + form + "', 'sec_form' : '" + sec_form + "', 'quantity' : '" + quantity + "'}";
            $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/addToBasket',
                data: JSONData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    $('#basketItems').html(data.d);
                    $('#basket').show();
                    that.parents('.row').find('.addStatus').html("added").show().animate({ opacity: 1 }, 1000).fadeOut(500);

                }

            });
        }
        return false;

    });

    // Update basket
    $('.updateButton A').live('click', function() {
        var that = $(this);

        var quantity = $(this).parents('.row').find('input').val();
        var itemId = $('.row').index($(this).parents('.row'));

        var JSONData = "{'itemIndex': " + itemId + ", 'quan': " + quantity + "}";
        $.ajax({
            type: "POST",
            url: '/designerplants/basket.aspx/updateBasket',
            data: JSONData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                that.parents('.row').find('.price').html("£" + data.d);
                that.hide().parents('.row').find('.updateStatus').html("updated").show().animate({ opacity: 1 }, 1000).fadeOut(500, function() { that.fadeIn(500) });

            }

        });

        return false;

    });

    // Update basket
    $('.removeButton A').live('click', function() {
        var that = $(this);

        var itemId = $('.row').index($(this).parents('.row'));

        var JSONData = "{'itemIndex': " + itemId + "}";
        $.ajax({
            type: "POST",
            url: '/designerplants/basket.aspx/deleteFromBasket',
            data: JSONData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                that.parents('.row').hide('fast').remove();
            }

        });

        return false;

    });

    // Submit Quote
    $('.submitQuote A').live('click', function() {
        $.ajax({
            type: "POST",
            url: '/designerplants/basket.aspx/submitQuote',
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                $('.checkout').find('.row').hide();
                $('.checkoutIntro').html('Your quote has been submitted');
                $('.submitQuote').hide();
                $('.sectionTitle').hide();
            }

        });

        return false;

    });

    // TRADE CAT SHOW/HIDE    
    $('.row .arrow').live('click', function() {

        if ($(this).parent('.row').find('.productDescription').hasClass('open')) {

            // Check if open, if open slide up
            $(this).parent('.row').find('.productDescription').slideUp(function() {
                $(this).parent('.row').find('.productDescription').removeClass('open');

                $(this).parent('.row').find('.arrow A').css({ backgroundPosition: '0 0' });
            });

        } else {

            // If not open, slide down
            $(this).parent('.row').find('.productDescription').slideDown(function() {
                $(this).parent('.row').find('.productDescription').addClass('open');

                $(this).parent('.row').find('.arrow A').css({ backgroundPosition: '0 -15px' });
            });
        }

        return false;

    });
    
    // Expand / Contract quotes
    
    $('.quoteContainer, .quoteExpander').click(function() {
    var quoteBody;
    var quoteExpander;
    if ($(this).is('.quoteExpander')) {
        quoteBody = $(this).parents('.quoteContainer').find('.quoteBody');
        quoteExpander = $(this);
    }
    else {
        quoteBody = $(this).find('.quoteBody');
        quoteExpander = $(this).find('.quoteExpander');
    }
        if (quoteBody.is(':visible')) {
            quoteBody.slideUp('fast');
            quoteExpander.removeClass('open');
        }
        else {
            quoteBody.slideDown('fast');
            quoteExpander.addClass('open');
        }
        return false;
    });
    

    $('.login a').click(function() {
        var JSONData = "{'email': '" + $('#txt_loginEmail').val() + "', 'password': '" + hex_md5($('#txt_loginPassword').val()) + "'}";
        $.ajax({
            type: "POST",
            url: 'methods/methods.aspx/logIn',
            data: JSONData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                result = JSON.parse(data.d);
                if (result.success) {
                    window.location = "/designerplants/tradeCat.aspx";
                }
                else {
                    if (result.errorMessage != "Server Error") {
                        $('#loginError').html("<span class=\"error\">" + result.errorMessage + "</span>");
                    }
                    else {
                        $('#loginError').html("<span class=\"error\">There was an error logging you in, please try again later</span>");
                    }
                }

            },
            failure: function(data) {
                $('#loginError').html("<span class=\"error\">There was an error logging you in, please try again later</span>");
            }
        });
        return false;

    });

});


function setDropdowns() {

    // Hide secondary forms to start with
    $('.sec_form').hide();
    
    // Get forms from size selection
    $('.size').change(function() {
        var formsDropdown = $(this).parents('.TVI-form').find('SELECT.form');
        if (formsDropdown != undefined && !$(this).is('.set')) {
            var plant = $(this).parents('.row').find('.name').html()
            var JSONData = "{'size': '" + $(this).val() + "', 'plant': '" + plant + "'}";
            if ($(this).val() == 'Size') {
                // Allow the other dropdown to repopulate this one
                formsDropdown.removeClass('set');
                
            }
            else {
                // Add class to stop the other dropdown causing this one to repopulate!
                formsDropdown.addClass('set');
                
            }
            $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/returnForms',
                data: JSONData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    data = JSON.parse(data.d);
                    formsDropdown.empty();
                    formsDropdown.append("<option value=\"Form\">Form</option>");
                    for (var i in data.forms) {
                        formsDropdown.append("<option value=\"" + data.forms[i] + "\">" + data.forms[i] + "</option>");
                    }

                }
            });
        }
        else {
            var secFormsDropdown = $(this).parents('.TVI-form').find('SELECT.sec_form');
            var plant = $(this).parents('.row').find('.name').html()
            var JSONData = "{'form': '" + formsDropdown.val() + "', 'plant': '" + plant + "','size': '" + $(this).val() + "'}";

            $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/returnSec_forms',
                data: JSONData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    data = JSON.parse(data.d);
                    secFormsDropdown.empty();
                    secFormsDropdown.append("<option value=\"Form\">Sec Form</option>");
                    secFormsDropdown.hide();
                    for (var i in data.sec_forms) {
                        secFormsDropdown.append("<option value=\"" + data.sec_forms[i] + "\">" + data.sec_forms[i] + "</option>");
                        secFormsDropdown.show();
                    }

                }
            });
        }
    });
    
    // Get sizes from form selection
    $('.form').change(function() {
        var sizesDropdown = $(this).parents('.TVI-form').find('SELECT.size');
        if (sizesDropdown != undefined && !$(this).is('.set')) {
            var plant = $(this).parents('.row').find('.name').html()
            var JSONData = "{'form': '" + $(this).val() + "', 'plant': '" + plant + "'}";
            if ($(this).val() == 'Form') {
                // Allow the other dropdown to repopulate this one
                sizesDropdown.removeClass('set');
            }
            else {
                // Add class to stop the other dropdown causing this one to repopulate!
                sizesDropdown.addClass('set');
            }
            $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/returnSizes',
                data: JSONData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    data = JSON.parse(data.d);
                    sizesDropdown.empty();
                    sizesDropdown.append("<option value=\"Size\">Size</option>");
                    for (var i in data.sizes) {
                        sizesDropdown.append("<option value=\"" + data.sizes[i] + "\">" + data.sizes[i] + "</option>");
                    }
                }
            });
        }
        else {
            var secFormsDropdown = $(this).parents('.TVI-form').find('SELECT.sec_form');
            var plant = $(this).parents('.row').find('.name').html()
            var JSONData = "{'form': '" + $(this).val() + "', 'plant': '" + plant + "','size': '" + sizesDropdown.val() + "'}";

            $.ajax({
                type: "POST",
                url: '/designerplants/tradeCat.aspx/returnSec_forms',
                data: JSONData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    data = JSON.parse(data.d);
                    secFormsDropdown.empty();
                    secFormsDropdown.append("<option value=\"Form\">Sec Form</option>");
                    secFormsDropdown.hide();
                    for (var i in data.sec_forms) {
                        secFormsDropdown.append("<option value=\"" + data.sec_forms[i] + "\">" + data.sec_forms[i] + "</option>");
                        secFormsDropdown.show();
                    }

                }
            });
        }
    });
}

function isValidEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return (reg.test(email))
}
