/// <reference path="jquery-vsdoc.js" />

var membershipButtonId = '';

$(document).ready(function() {
    $('input[type="text"]').each(function() {
        if ($(this).attr('title') != '' && $(this).val() == '')
            $(this).val($(this).attr('title'))
    });
    
    $('input[type=text]').click(function() {
        if ($(this).val() == $(this).attr('title'))
            $(this).val('');
    }).blur(function() {
        if ($(this).val() == "")
            $(this).val($(this).attr('title'));
    });

    /*
    ##########################################################################################
    depending on the type of player being used in the comp slider and feature panel
    please swap between the 2 sets of functions to control them.
    ##########################################################################################
    */
    
    //competitions slider functions with in banner video player
    
    $('#competition-slider.withoutpopup li').click(function() {
        if (!$(this).hasClass('open')) {
            var openobjectID = $('#competition-slider li.open .panel').find('object').attr('id');
            if ($('#competition-slider li.open').hasClass('last')) {
                $('#' + openobjectID).remove();
                $('#competition-slider li.open .panel').prepend('<div id="' + openobjectID + '"></div>');
                $('#competition-slider li.open').animate({ width: "74px" }, { queue: false, duration: 400 }).removeClass('open');                
            } else {
                $('#' + openobjectID).remove();
                $('#competition-slider li.open .panel').prepend('<div id="' + openobjectID + '"></div>');
                $('#competition-slider li.open').animate({ width: "75px" }, { queue: false, duration: 400 }).removeClass('open');
            }
            if ($(this).hasClass('last')) {
                $(this).animate({ width: "715px" }, { queue: false, duration: 400 });
            } else {
                $(this).animate({ width: "716px" }, { queue: false, duration: 400 });
            }
            $(this).addClass('open');            
            insertCompFlash($(this).find('.panel'));
        }
    });  
    
    
    /* Competition in banner video player */
    
    if ($('#competition-slider.withoutpopup').length != 0)
        insertCompFlash($('#competition-slider.withoutpopup li .panel'));
    
    
    //competitions slider functions with popup video player
    $('#competition-slider li').click(function() {
        //alert('clicked');
        if (!$(this).hasClass('open')) {
            if ($('#competition-slider li.open').hasClass('last')) {
                $('#competition-slider li.open').animate({ width: "74px" }, { queue: false, duration: 400 }).removeClass('open');                
            } else {
                $('#competition-slider li.open').animate({ width: "75px" }, { queue: false, duration: 400 }).removeClass('open');
            }
            if ($(this).hasClass('last')) {
                $(this).animate({ width: "715px" }, { queue: false, duration: 400 }).css('display', 'block');
            } else {
                $(this).animate({ width: "716px" }, { queue: false, duration: 400 }).css('display', 'block');
            }
            $(this).addClass('open');            
        }
    });
    $('#competition-slider li').hover(function() {
        //alert('hovering');
    }, function() {
        // Stuff to do when the mouse leaves the element;
    });
    
    /* Competition popup video player */
    /*$(".competition-video").fancybox({
        'width'				: 640,
        'height'			: 380,
        'autoScale'     	: false,
        'titleShow'         : false,
        'transitionIn'		: 'none',
        'transitionOut'		: 'none',
        'type'				: 'iframe'
    });*/
    
    //set current comp image nav style
    $('#competition-nav li').each(function(index) {
        if ($(this).hasClass('current')) {
            var navImage = $(this).find('img'),
            mainImage = $(navImage).attr('src'),
            hoverIMage = $(navImage).attr('rel');
            $(navImage).attr({ src: hoverIMage, rel: mainImage });
        }   
    });
    
    //comp nav roll overs
    $('#competition-nav a img').hover(function() {
        if (!$(this).parent().parent().hasClass('current')){
            var mainImage = $(this).attr('src'),
                hoverIMage = $(this).attr('rel');
            $(this).attr({ src: hoverIMage, rel: mainImage });
        }
    }, function() {
        if (!$(this).parent().parent().hasClass('current')){
            var mainImage = $(this).attr('src'),
                hoverIMage = $(this).attr('rel');
            $(this).attr({ src: hoverIMage, rel: mainImage });
        }
    });

    //build the comps pager if on the comps page
    if ($('#current-competitions').length != "0") buildPager();

    //comps pager click functions
    $('#current-competitions #pager a').click(function() {
        if (!$(this).hasClass('current')) {
       
            var currentID = $(this).attr('id');
            console.log('Current page: '+currentID);
            
            var currentPageStartItem = (currentID*maxItems)-1;
            var currentPageEndItem = currentPageStartItem + 1;
            console.log('Current start item: '+currentPageStartItem);
            console.log('Current end item: '+currentPageEndItem);
            
            $('#current-competitions #pager a').removeClass('current');
            $('#previous-winners li').addClass('hidden');
            
            var maxItem = (maxItems * currentID);
            var minItem = maxItem - maxItems;
            console.log('higest to show: '+maxItem);
            console.log('lowest to show: '+minItem);
            
            $(this).addClass('current');
            for (var i = minItem; i < maxItem; i++) {
                var toShow = $('#previous-winners li')[i];
                $(toShow).removeClass('hidden');
            }
        }
        return false;
    }); 
    
    $('#registration-cancel').click(function() {
        parent.closeMembership();
    });

});

function insertCompFlash(panel) {
    var currentDate = new Date();
    var xml = $(panel).find('.videopath').html() + '&time=' + currentDate.getTime();
    var params = {
        wmode: "transparent",
        allowscriptaccess: "always",
        allowfullscreen: "true",
        bgcolor: "#000000"
    };
    var attributes = {
        id: $(panel).find('div').attr('id'),
        name: "video_player"
    };
    var flashvars = {
        XmlUrl: xml
    };
    swfobject.embedSWF("/Common/Flash/TV_player_b4.swf", $(panel).find('div').attr('id'), "640", "360", "9.0.115", "", flashvars, params, attributes, swfObjectCallback);
}

function swfObjectCallback(e) {
    console.log("e.success = " + e.success +"\ne.id = "+ e.id +"\ne.ref = "+ e.ref);
}

function closeMembership() {
    parent.$.fancybox.close();
    $('.hidden-membership-field').val('membership skipped');
    $('#' + membershipButtonId).click();
}

var numItems,
    pages,
    maxItems = 2;

function buildPager() {
    //hide all the items, count how many there are, work out the number of pages based on total and max items per page, 
    //Add in the page numbers based on the number of pages calculation, 
    //then only show the first number of items for the set page size
    $('#previous-winners li').addClass('hidden');
    numItems = $('#previous-winners li').length;
    console.log('Number of Items: ' + numItems);
    pages = Math.ceil(numItems / maxItems);
    console.log('Pages: ' + pages);
    $('#current-competitions').append('<ol id=\"pager\"><li class=\"label\">Go to page</li></ol>');
    for (var i = 1; i <= pages; i++) {
        if ([i] == 1) {
            $('#pager').append('<li><a class=\"current\" href=\"#\" id=\"' + [i] + '\">' + [i] + '</a></li>');
        }
        else {
            $('#pager').append('<li><a href=\"#\" id=\"' + [i] + '\">' + [i] + '</a></li>');
        }        
    }
    for (var i = 0; i < maxItems; i++) {
        var selected = $('#previous-winners li')[i];
        $(selected).removeClass('hidden');
    }
}

function validateForm(buttonID, formClientSideId) {
    
    var errorMessage = '',
        isValid = true;

    membershipButtonId = buttonID;

    $('.' + formClientSideId + ' li.required').each(function(index) {
        if($(this).attr('class').indexOf('textbox') != -1 || $(this).attr('class').indexOf('date') != -1 || $(this).attr('class').indexOf('select') != -1|| $(this).attr('class').indexOf('textfield') != -1) {
            if ($(this).find('input, select, textarea').val() == '') {
                console.log('i\'m a normal error: ' + $(this).find('label').html());
                isValid = false;
                errorMessage += $(this).find('label').html() + ' is empty \r\n';
                return;
            }
            if ($(this).find('label').attr('rel') == 'Barcode') {
                if ($(this).find('input, textarea').val().match(/,/g)) {
                    isValid = false;
                    errorMessage += $(this).find('label').html() + ' is incorrectly formatted, please check \r\n';
                    return;
                }
            }
        }
        if ($(this).attr('class').indexOf('inline-checkbox') != -1) {
            if ($(this).find('input').attr('checked') == '') {
                console.log('i\'m an inline checkbox error: ' + $(this).find('label').html());
                isValid = false;
                errorMessage += $(this).find('label').html() + ' is not checked \r\n';
            }
            return;
        }
        if ($(this).attr('class').indexOf('checkbox') != -1 || $(this).attr('class').indexOf('radio') != -1) {
            var isChecked = false;
            console.log('I\'m a radio or check');
            $(this).find('input').each(function(index) {
                if ($(this).attr('checked') != '')
                    isChecked = true;
            });
            if (isChecked == false) {
                console.log('i\'m a checkbox or select error: ' + $(this).find('label').html());
                isValid = false;
                errorMessage += $(this).find('label').html() + ' is not checked \r\n';
                return;
            }
        }
    });
    
    //validate the emails in the send to a friend form on the comps page
    if ($('.' + formClientSideId).hasClass('.orchardSendToFriendForm')) {
        console.log('send friend');
        var validationRegEx = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum|co.uk|com.au|co.nz)\b/;
         $('.' + formClientSideId + ' li.required').each(function(index) {
            if ($(this).find('label').attr('rel').indexOf('Email') != -1) {
                if (!validationRegEx.test($(this).find('input').val())) {
                    isValid = false;
                    errorMessage += $(this).find('label').html() + ' is incorrectly formatted, please check \r\n';
                    return;
                }
            }
         });
    }
    
    if (!isValid) {
        alert(errorMessage);
        return false;
    }
    //show memebership pop up after form valisdation but before submit
    if ($('.hidden-membership-field').length != 0 && $('.hidden-membership-field').val() != 'membership skipped' && !$('.'+formClientSideId).hasClass('orchardSendToFriendForm') ) {
        
        //grab static form values that are default database fields
        var FirstName = $('.' + formClientSideId + ' li').find('label[rel="First Name"]').next().val(),
            LastName = $('.' + formClientSideId + ' li').find('label[rel="Last Name"]').next().val(),
            Email = $('.' + formClientSideId + ' li').find('label[rel="Email"]').next().val(),
            Mobile = $('.' + formClientSideId + ' li').find('label[rel="Mobile"]').next().val(),
            Address1 = $('.' + formClientSideId + ' li').find('label[rel="Address 1"]').next().val(),
            Address2 = $('.' + formClientSideId + ' li').find('label[rel="Address 2"]').next().val(),
            Suburb = $('.' + formClientSideId + ' li').find('label[rel="Suburb"]').next().val(),
            PostCode = $('.' + formClientSideId + ' li').find('label[rel="Postcode"]').next().val();
            
        console.log(FirstName);
        $.fancybox({
            //'orig': $(this),
            'padding': 0,
            'href': '/Competitions/MembershipForm.aspx?FirstName=' + FirstName + '&LastName=' + LastName + '&Email=' + Email + '&Mobile=' + Mobile + '&Address1=' + Address1 + '&Address2=' + Address2 + '&Suburb=' + Suburb + '&PostCode=' + PostCode,
            'modal': true,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'type': 'iframe',
            'width': 710,
            'height': 600
        });
        return false; 
    }

    return true;
}