
$(document).ready(function() {

    // Resize thumbnails according to empty spaces in p.info and p.action-info
    if ($("div.thumbnail").length > 0) {
        // Create array
        var thumbnailRow = {}
        // For each thumbnail push object in the array thumbnailRow by top position [top position means thumbnail line]
        $("div.product-thumbnail-wrapper ul li").each(function(index, domEle) {
            // Get thumbnail top position
            var position = $(this).position().top;
            // Check if thumbnail top position is null
            if (thumbnailRow[position] == null) {
                thumbnailRow[position] = new Array();
            }
            // Push JQuery object(thumbnail) into thumbnailRow array (line)
            thumbnailRow[position].push(domEle);
        });
        // Create array
        var thumbnailRowGroup = new Array();
        // For each thumbnailRow (line) push into line
        for (var topPosition in thumbnailRow) {
            // Push each row to rowGroup
            thumbnailRowGroup.push($(thumbnailRow[topPosition]));
        }
        // For each line group
        for (var i = 0; i < thumbnailRowGroup.length; i++) {
            /************ p.info control ************/
            // Set has info to false
            var HasInfo = false;
            // For each thumbnail 
            thumbnailRowGroup[i].each(function() {
                // Create variable with p.info content
                var text = $(this).find("p.info").text();
                // Checks if p.info has content
                if (text.length > 0) {
                    // Set has action info to true
                    HasInfo = true;
                }
            });
            // If all thumbnail in the the same line doesn't have action info
            if (!HasInfo) {
                // For each thumbnail (in the same line)
                thumbnailRowGroup[i].each(function() {
                    // Reset p.info styles
                    $(this).find("p.info").css("padding", "0px");
                    $(this).find("p.info").css("height", "auto");
                });
            }
            /************ p.action-info control ************/
            // Set has action info to false
            var HasActionInfo = false;
            // For each thumbnail 
            thumbnailRowGroup[i].each(function() {
                // Create variable with p.action-info content
                var text = $(this).find("p.action-info").text();
                // Checks if p.action-info has content
                if (text.length > 0) {
                    // Set has action info to true
                    HasActionInfo = true;
                }
            });
            // If all thumbnail in the the same line doesn't have action info
            if (!HasActionInfo) {
                // For each thumbnail (in the same line)
                thumbnailRowGroup[i].each(function() {
                    // Reset p.action-info styles
                    $(this).find("p.action-info").css("padding", "0px");
                    $(this).find("p.action-info").css("height", "auto");
                });
            }
            /************ p.action2 control ************/
            // Set has action2 (Remove from my favourites) to false
            var HasAction2 = false;
            // For each thumbnail 
            thumbnailRowGroup[i].each(function() {
                // Create variable with p.action-info content
                var text = $(this).find("p.action2").text();
                // Checks if p.action2 has content
                if (text.length > 0) {
                    // Set has action2 to true
                    HasAction2 = true;
                }
            });
            // If all thumbnail in the the same line doesn't have action2
            if (!HasAction2) {
                // For each thumbnail (in the same line)
                thumbnailRowGroup[i].each(function() {
                    // Reset p.action2 styles
                    $(this).find("p.action2").css("padding", "0px");
                    $(this).find("p.action2").css("height", "auto");
                });
            }
        }
    }


    $("div.categories-wrapper div.categories ul.second-level li a").each(function() {
        if ($(this).height() > 20) {
            $(this).css({ 'line-height': '11px' });
            if ($.browser.msie && $.browser.version < 7)
                $(this).css({ 'padding': '4px 0px 4px 15px' });
            else
                $(this).css({ 'padding': '3px 0px 7px 15px' });

        }
    });

    $("div.categories-wrapper div.categories ul.third-level li a").each(function() {
        if ($(this).height() > 20) {
            $(this).css({ 'line-height': '11px' });
            if ($.browser.msie && $.browser.version < 7)
                $(this).css({ 'padding': '4px 0px 4px 30px' });
            else
                $(this).css({ 'padding': '3px 0px 7px 30px' });
        }
    });

    $("div.categories-wrapper div.categories ul.fourth-level li a").each(function() {
        if ($(this).height() > 20) {
            $(this).css({ 'line-height': '11px' });
            if ($.browser.msie && $.browser.version < 7)
                $(this).css({ 'padding': '4px 0px 4px 45px' });
            else
                $(this).css({ 'padding': '3px 0px 7px 45px' });
        }
    });

    // Check if the html page have tag 'img' with 'product-tag' class
    if ($("img.product-tag").length > 0) {
        // Apply transparency fix for IE6
        $("img.product-tag").ifixpng();
    }

    // Check if the html page have tag 'img' with 'icon' class
    if ($("img.icon").length > 0) {
        // Apply transparency fix for IE6
        $("img.icon").ifixpng();
    }

    // Check if the browser is IE and less than 7 
    if ($.browser.msie && $.browser.version < 7) {
        $(window).scroll(function() {
            var top = $(this).scrollTop();
            // Seg the minicart always on the top
            $('#mini-cart').css('top', top + 10 + "px");
        });
    }

    // Show Mini Cart

    $("#header .second-layer .third-layer .first-link ul li.cart-link a").click(function() {
        $("#mini-cart").show('slow');
        return false;
    });

    $("input.add-to-cart").click(function() {
        /************ Add the new item to the mini cart and move the last item into the next row ****************/
        var id = $(this).attr("id").substring(4);
        var newItem = $($.MimicCallback(parseInt(id)));
        var newItemId = newItem.find("input[type='hidden']").attr("value");
        var existingItem = null;
        $("div#mini-cart div.middle div").each(function() {
            var id = $(this).find("input[type='hidden']").attr("value");
            if (id == newItemId)
                existingItem = $(this);
        });

        var isSeperatorRequired = false;
        var count = 0;
        $("div#mini-cart div.middle div.item").each(function() {
            count = count + 1;
        });

        // This is the HTML for the seperator between the items already added to the cart
        var seperatorHTML = '<div class=\"seperator\">' +
            '<div class=\"solid\"></div>' +
            '</div>';

        if (existingItem != null) {
            // The item already exists so we just need to update the quantity and make it the first item if it isn't
            if (existingItem.is(".last-item")) {
                // Simply update the quantity by 1
                var lastItemQuantity = existingItem.find("p.quantity").html();
                var updatedItemQuantity = parseInt(lastItemQuantity);
                updatedItemQuantity = updatedItemQuantity + 1;
                existingItem.find("p.quantity").html(updatedItemQuantity);

                /**/
                var last_item = $(".last-item p.price span.special").calc(
                // the equation to use for the calculation
		            "qty * price",
                // define the variables used in the equation, these can be a jQuery object
		            {
		            qty: $("p.quantity"),
		            price: $("p.unit-price")
		        },
                // define the formatting callback, the results of the calculation are passed to this function
	                function(s) {
	                    // return the number as a dollar amount
	                    return "$" + s.toFixed(2);
	                },
                // define the finish callback, this runs after the calculation has been complete
	                function($this) {
	                    // sum the total of the $("[id^=total_item]") selector
	                    var sum = $this.sum();
	                    $(".last-item p.price span.special").text(
	                    // round the results to 2 digits
			                "$" + sum.toFixed(2)
		                );
	                }

		        );

            }
            else if (existingItem.is(".item")) {
                // Move the current last item to the next row so that the existing item quantity being updated
                // can be bumped up as the last item with an updated quantity.
                var lastItemDescription = $("div#mini-cart div.middle div.last-item p.description").html();
                var lastItemQuantity = $("div#mini-cart div.middle div.last-item p.quantity").html();
                var lastUnitItemPrice = $("div#mini-cart div.middle div.last-item p.unit-price").html();
                var lastItemPrice = $("div#mini-cart div.middle div.last-item p.price span.special").html();
                var itemId = $("div#mini-cart div.middle div.last-item input[type='hidden']").attr("value");
                var newItemHTML = '<div class=\"item\">' +
                    '<p class=\"description\">' + lastItemDescription + '</p>' +
                    '<p class=\"quantity\">(' + lastItemQuantity + ')</p>' +
                    '<p class=\"unit-price\">' + lastUnitItemPrice + '</p>' +
                    '<p class=\"value\">' + lastItemPrice + '</p>' +
                    '<input type=\"hidden\" value=\"' + itemId + '\" />' +
                    '</div>';
                $("div#mini-cart div.middle div.header:last").after(newItemHTML);
                var existingQuantity = existingItem.find("p.quantity").html().substring(1, 2);
                var updatedItemQuantity = parseInt(existingQuantity);
                updatedItemQuantity = updatedItemQuantity + 1;

                // Remove the existing because it till go to the top of the list with an updated quantity
                existingItem.remove();

                newItem.find("p.quantity").html(updatedItemQuantity);

                $("div#mini-cart div.middle div.last-item").html(newItem.html());

                /**/
                var item = $(".item p.value").calc(
                // the equation to use for the calculation
		            "qty * price",
                // define the variables used in the equation, these can be a jQuery object
		            {
		            qty: $("p.quantity"),
		            price: $("p.unit-price")
		        },
                // define the formatting callback, the results of the calculation are passed to this function
	                function(s) {
	                    // return the number as a dollar amount
	                    return "$" + s.toFixed(2);
	                },
                // define the finish callback, this runs after the calculation has been complete
	                function($this) {
	                    // sum the total of the $("[id^=total_item]") selector
	                    var sum = $this.sum();
	                    $(".item p.value").text(
	                    // round the results to 2 digits
			                "$" + sum.toFixed(2)
		                );
	                }
		        );

            }
        }
        else {
            // The item doesn't exist in the cart yet so add it to the top of the list while bumping the
            // current item at the top to the next row below
            var lastItemDescription = $("div#mini-cart div.middle div.last-item p.description").html();
            var lastItemQuantity = $("div#mini-cart div.middle div.last-item p.quantity").html();
            var lastUnitItemPrice = $("div#mini-cart div.middle div.last-item p.unit-price").html();
            var lastItemPrice = $("div#mini-cart div.middle div.last-item p.price span.special").html();
            var itemId = $("div#mini-cart div.middle div.last-item input[type='hidden']").attr("value");
            var newItemHTML = '<div class=\"item\">' +
                    '<p class=\"description\">' + lastItemDescription + '</p>' +
                    '<p class=\"quantity\">(' + lastItemQuantity + ')</p>' +
                    '<p class=\"unit-price\">' + lastUnitItemPrice + '</p>' +
                    '<p class=\"value\">' + lastItemPrice + '</p>' +
                    '<input type=\"hidden\" value=\"' + itemId + '\" />' + // This hidden field exists to hold the ID of the item in the
            // cart so that we can check for existing items to update 
            // the quantity.
                    '</div>';
            // Check if the the system is adding a product for the first time
            if (lastItemDescription != null) {
                $("div#mini-cart div.middle div.header:last").after(newItemHTML);
            }
            $("div#mini-cart div.middle div.last-item").html(newItem.html());
        }
        $("div#mini-cart div.middle div.seperator").remove();
        $("div#mini-cart div.middle div.item").not("div#mini-cart div.middle div.item:first").before(seperatorHTML);
        // Get the sum of the elements
        var last_item = $(".last-item p.price").sum();
        // Get the sum of the elements
        var item = $(".item p.value").sum();
        // Get the sum of the elements
        var additional_cost = $(".additional-cost p.value").sum();
        // Sum all the items
        var sum = last_item + item + additional_cost;
        // Format to 2 decimal places
        var sum = parseFloat(sum).toFixed(2);
        // Update the total
        $("#total-cost").text("$" + sum.toString());

        /***********************************************************************************************************/
        $("#mini-cart").show('slow');
        return false;
    });
    // Hide Mini Cart
    $("a#exit").click(function() {
        $("#mini-cart").hide('slow');
        return false;
    });
    // Set up Dropdown Menu
    $(window).load(
        function() {
            // set the inital configuration for dropdown menu to avoid horizontal scroll
            $(".products-categories-wrapper").css({ "left": "0px" });
        }
    );
    // Show/Hide Dropdown Menu with alignment
    // This aligment support a full (width) dynamic dropdown menu.
    $("li.menu-item").hover(
        function() {
            // get the start position of the item in top menu
            var menuItemPosition = $(this).find(".item").offset().left; //x
            // get the final position of the header         
            var finalPosition = $("#header-limit").offset().left; //y      
            // Check if the browser is IE and less than 7 
            if ($.browser.msie && $.browser.version < 7) {
                // Handle the position in IE6
                finalPosition = finalPosition - 6;
            }
            // calc the available space between the item in top menu and final of the header
            var availableSpace = finalPosition - menuItemPosition;
            // get the width of the dropdown menu
            var pcwWidth = $(this).find(".products-categories-wrapper").width(); //z
            // check if the size (width) of the dropdown menu is bigger than the available space
            if (pcwWidth > availableSpace) {
                // set the differece as the offset
                offSet = availableSpace - pcwWidth;
                // reset the initial configuration of dropdown menu
                $(this).find(".products-categories-wrapper").css({ "left": "" });
                // set the left margin according to the offset
                $(this).find(".products-categories-wrapper").css({ "margin": "0px 0px 0px " + offSet + "px" });

            } else {
                // reset the initial configuration of dropdown menu
                $(this).find(".products-categories-wrapper").css({ "left": "" });
                // force the margin to zero (to avoid problems for crossing browsers)
                $(this).find(".products-categories-wrapper").css({ "margin": "0px 0px 0px 0px" });
                // Check if the browser is IE and less than 7 
                if ($.browser.msie && $.browser.version < 7) {
                    // set the left margin according to the offset
                    $(this).find(".products-categories-wrapper").css({ "margin": "0px 0px 0px -6px" });
                }
            }
            // Show dropdown menu
            $(this).find(".products-categories-wrapper").css({ "visibility": "visible" });
        } /**/,
        function() {
            // Hide dropdown menu
            $(this).find(".products-categories-wrapper").css({ "visibility": "hidden" });
        }
    );
    $("div.gift-list #EnterDrawButton").click(function() {
        var code = $.trim($("div.gift-list #TransactionCodeInput").val()).length > 0;
        var phone = $.trim($("div.gift-list #PhoneNumberInput").val()).length > 0;
        var termsConditions = $("div.gift-list #TermsConditionsCheck").is(':checked');
        if (!code & phone & termsConditions) {
            $("div.gift-list div.error-panel p").text("Please enter your unique code or transaction number");
            return false;
        }
        else if (code & !phone & termsConditions) {
            $("div.gift-list div.error-panel p").text("Please enter your phone number");
            return false;
        }
        else if (code & phone & !termsConditions) {
            $("div.gift-list div.error-panel p").text("Please accept the terms and conditions");
            return false;
        }
        else if (!code & !phone & termsConditions) {
            $("div.gift-list div.error-panel p").text("Please enter your unique code or transaction number and phone number");
            return false;
        }
        else if (code & !phone & !termsConditions) {
            $("div.gift-list div.error-panel p").text("Please enter your phone number and accept the terms and conditions");
            return false;
        }
        else if (!code & phone & !termsConditions) {
            $("div.gift-list div.error-panel p").text("Please enter your unique code or transaction number and accept the terms and conditions");
            return false;
        }
        else if (!code & !phone & !termsConditions) {
            $("div.gift-list div.error-panel p").text("Please enter your code and phone number, and accept the terms and conditions");
            return false;
        }
        else {
            $("div.gift-list div.error-panel p").text("");
            return true;
        }
    });

    $("div.bts-list #EnterDrawButton").click(function() {
        var code = $.trim($("div.bts-list #TransactionCodeInput").val()).length > 0;
        var phone = $.trim($("div.bts-list #PhoneNumberInput").val()).length > 0;
        var school = $.trim($("div.bts-list #ChosenSchoolInput").val()).length > 0;
        var termsConditions = $("div.bts-list #TermsConditionsCheck").is(':checked');
        if (!termsConditions & code & phone & school) {
            $("div.bts-list div.error-panel p").text("Please accept the terms and conditions");
            return false;
        }
        var errorText = '';
        if (!code) {
            errorText = 'your unique code or transaction number ';
        }

        if (!phone) {
            if (errorText != '') {
                errorText += 'and '
            }
            errorText += 'your phone number ';
        }

        if (!school) {
            if (errorText != '') {
                errorText += 'and '
            }
            errorText += 'your chosen school ';
        }

        if (errorText != '') {
            $("div.bts-list div.error-panel p").text('Please enter ' + errorText);
            return false;
        }
        return true;
    });
});

// This is just a call back function for testing purposes. Intershop need to write their own ajax callback to handle the
// data to be returned when user clicks on 'Add to Cart' on the page.
$.MimicCallback = function(id) {
    // This is purely test data based on the specific 'Add to Cart' button that was clicked and is NOT supposed to make any sense
    switch (id) {
        case 1:
            return '<div><img class=\"product\" src=\"../Resources/Images/Minicart/dvd.jpg\" alt=\"Transonic DVD-R 10 Piece\" />' +
                '<p class=\"description\">Transonic DVD-R 10 Piece</p>' +
                '<label class=\"info\"></label>' +
                '<p class=\"info\"></p>' +
                '<label class=\"quantity\">Quantity:</label>' +
                '<p class=\"quantity\">1</p>' +
                '<p class=\"unit-price\">$9.99</p>' +
                '<p class=\"price\"><span class=\"special\">$9.99</span></p>' +
                '<input type=\"hidden\" value=\"1\" /></div>';
            break;
        case 2:
            return '<div><img class=\"product\" src=\"../Resources/Images/Minicart/tv.jpg\" alt=\"Transonic 32\" LCD Television TC-L3236\" />' +
                '<p class=\"description\">Transonic 32" LCD Television TC-L3236</p>' +
                '<label class=\"info\">Save:</label>' +
                '<p class=\"info\">$200.00</p>' +
                '<label class=\"quantity\">Quantity:</label>' +
                '<p class=\"quantity\">1</p>' +
                '<p class=\"unit-price\">$699.99</p>' +
                '<p class=\"price\"><span class=\"special\">$699.99</span></p>' +
                '<input type=\"hidden\" value=\"2\" /></div>';
            break;
        case 3:
            return '<div><img class=\"product\" src=\"../Resources/Images/Minicart/flashdrive.jpg\" alt=\"Transonic USB Flash Drive 4GB\" />' +
                '<p class=\"description\">Transonic USB Flash Drive 4GB</p>' +
                '<label class=\"info\"></label>' +
                '<p class=\"info\"></p>' +
                '<label class=\"quantity\">Quantity:</label>' +
                '<p class=\"quantity\">1</p>' +
                '<p class=\"unit-price\">$29.99</p>' +
                '<p class=\"price\"><span class=\"special\">$29.99</span></p>' +
                '<input type=\"hidden\" value=\"3\" /></div>';
            break;
        case 4:
            return '<div><img class=\"product\" src=\"../Resources/Images/Minicart/tv2.jpg\" alt=\"Sanyo 42" LCD Television LCD42CA9SZ\" />' +
                '<p class=\"description\">Sanyo 42" LCD Television LCD42CA9SZ</p>' +
                '<label class=\"info\">Save:</label>' +
                '<p class=\"info\">$500.00</p>' +
                '<label class=\"quantity\">Quantity:</label>' +
                '<p class=\"quantity\">1</p>' +
                '<p class=\"unit-price\">$999.00</p>' +
                '<p class=\"price\"><span class=\"special\">$999.00</span></p>' +
                '<input type=\"hidden\" value=\"4\" /></div>';
            break;
    }
};

