$(function(){
    $("a[rel='external']").click(function(){
        window.open(this.href);
        return false;
    });

    $('.productImage').tooltip({
        delay: 500,
        showURL: false,
        fade: 250,
        bodyHandler: function() {
            var classText = $(this).parent().attr('class');
            var parts = classText.split('|');
            var $element = $('<div class="tooltipHeader">' + parts[1] + '</div><div align="center" class="tooltipImage"><img src="/layout/Cdf/Images/Products/194x194/' + parts[0] + '.png"/></div>');
            return $element;
        }
    });

    $('.amountField').focus(function() {
        if (this.value == '1') {
            if (this.form.id != 'basketForm') {
                this.value = '';
            }
        }
    });
    $('.amountField').blur(function() {
        if (this.value == '') {
            this.value = '1';
        }
    });
});

$(document).ready(function() {

    $('.amountField').attr('autocomplete', 'off');

    var $email = $('#js-emailAddress').text();
    var $code = $('#js-promotionCode').text();

    blurField('#newsletterEmail', $email);
    blurField('#promotionCode', $code);
    blurField('#basketPromotionCode', $code);
    blurField('#promotionPromotionCode', $code);

    // newsletter
    $('#newsletterEmail').focus(function() {
        focusField('#newsletterEmail', $email);
    });
    $('#newsletterEmail').blur(function() {
        blurField('#newsletterEmail', $email)
    });
    // promotionCode
    $('#promotionCode').focus(function() {
        focusField('#promotionCode', $code);
    });
    $('#promotionCode').blur(function() {
        blurField('#promotionCode', $code)
    });
    // basket promotionCode
    $('#basketPromotionCode').focus(function() {
        focusField('#basketPromotionCode', $code);
    });
    $('#basketPromotionCode').blur(function() {
        blurField('#basketPromotionCode', $code)
    });
    // promotion promotionCode
    $('#promotionPromotionCode').focus(function() {
        focusField('#promotionPromotionCode', $code);
    });
    $('#promotionPromotionCode').blur(function() {
        blurField('#promotionPromotionCode', $code)
    });
});

function focusField($fieldId, $fieldValue)
{
    if ($($fieldId).attr('value') == $fieldValue) {
        $($fieldId).css('color', '#000');
        $($fieldId).attr('value', '');
    }
}

function blurField($fieldId, $fieldValue)
{
    if ($($fieldId).attr('value') == '') {
        $($fieldId).css('color', '#848484');
        $($fieldId).attr('value', $fieldValue);
    }
}

function errorTooltip(error, element)
{
    element.tooltip({
        delay: 500,
        showURL: false,
        fade: 250,
        bodyHandler: function() {
            return error;
        }
    });
}