$(document).ready(function() {

    /** media center **/
    if($('.tab-links').length) {
        $('.tab-links li:first, .tab-entries .tab-entry:first').addClass('current');

        $('.tab-links a').click(function() {

            $(this).parent().addClass('current').siblings('.current').removeClass('current');

            var targ = $(this).attr('href');

            $(targ).addClass('current').siblings('.current').removeClass('current');

            return false;

        });

    }	

	

	

    $('a[class*="colorbox2"]').bind('click', function(e) {

        var item_url = $(this).attr('href');

        if($(this).parents('.item-gallery').length) {
            $(this).parent().addClass('c-clicked');
        }

        $.colorbox({
            href: item_url,
            initialWidth: 30,
            initialHeight: 30,
            onComplete: function() {
                if($('#cboxLoadedContent .media-popup').length) {
                    if($('.popup-gallery').length) {
                        $('.popup-gallery .large').append('<ul />');

                        var items_length = $('.popup-gallery .small li').length;
                        
                        for(i=1;i<=items_length;i++) {
                            var $item = $('.popup-gallery .small li').eq(i-1);
                            var img_src = $item.find('a').attr('href');
                            $('.popup-gallery .large ul').append('<li><img src="' + img_src + '" /></li>');
                            $item.find('a').attr('href', '#');
                        }

                        $('.popup-gallery .large ul').jcarousel({
                            visible: 1,
                            scroll: 1,
                            animation: 700,
                            easing: 'easeInOutQuart',
                            wrap: 'both',
                            initCallback: function(carousel) {},
                            itemFirstInCallback: function(carousel,item,idx,state) {
                                var $item = $('.popup-gallery .small li').eq(idx-1);
                                var img_desc = $item.find('.notext').text();
                                $('.popup-gallery .text p').text(img_desc);
                                $item.addClass('current').siblings('.current').removeClass('current');

                                if(idx > 5) {
                                    $('.popup-gallery .small ul').data('jcarousel').scroll(idx);
                                } else {
                                    if($('.popup-gallery .small ul').data('jcarousel') != undefined) {
                                        $('.popup-gallery .small ul').data('jcarousel').scroll($.jcarousel.intval(1));
                                    }
                                }
                            }
                        });


                        $('.popup-gallery .small ul').jcarousel({
                            scroll: 1,
                            visible: 5,
                            wrap: 'both',
                            itemFallbackDimension: 80,
                            initCallback: function(carousel) {
                                if($('.c-clicked').length) {
                                    var c_idx = $('.c-clicked').index();
                                    $('.c-clicked').removeClass('c-clicked');
                                    $('.popup-gallery .large ul').data('jcarousel').scroll($.jcarousel.intval(c_idx+1));
                                }

                                $('.popup-gallery .small a').live('click', function() {
                                    var t_idx = $(this).parent().index();
                                    $('.popup-gallery .large ul').data('jcarousel').scroll($.jcarousel.intval(t_idx+1));
                                    return false;
                                });
                            }
                        });
                    }
                }
                $.colorbox.resize();
            },
            scrolling: false
        });

        return false;
    });	
	

    /** END media center **/

    /* COMPETITION POPUPS **/
    // neeed to have them seperate from the generic triggering of the colorbox 
    // lightbox by simply having 'colorbox' as the class name of the anchor element
    // problem was the close button wouldnt custom close buttons weren't closing lightbox'
    $('#big-awareness, .big-awareness_lnk').click(function(e){
        e.preventDefault();
        awarenessCompetition();
    });
    
    $('#kids-campaign').click(function(e){
        e.preventDefault();
        competition();
    });

    $('#kids-campaign2').click(function(e){
        e.preventDefault();
        competition2();
    }); 
    
    
    /** TOP RATED RECIPES SLIDER */
    $(".featured-tabs ul li a").click(function() {
        if( $(this).parent().index() == 0 )
            $("#featured .shell").removeClass("active-shell");
        else
            $("#featured .shell").addClass("active-shell");

        return false;
    });

    init_carousel();
    $('#carousel_arrow_left').bind('click', function(e) {
        e.preventDefault();
        move_carousel_left();
    });

    $('#carousel_arrow_right').bind('click', function(e) {
        e.preventDefault();
        move_carousel_right();
    });
    /** END TOP RATED RECIPES SLIDER */

    /** QUICK RECIPE SEARCH SLIDER */
    $('#small-slider ul li a img[class!=active]').click(function(e){       
        e.preventDefault();
        var category = $(this).attr('id'); // get the clicked category 
        $('input[name=quick_category]').val('').val(category); // set the category for POST this should hold for whether categroy is quick_ or adv_
        
        
        // get the necessary variables for image path
        // change image
        var template  = $('input[name=template]').val();
        var site      = $('input[name=site]').val();
        
        // make the category name in uppercase so we can locate the rollover image for the category when clicked
        var ucCategory  =  category.substr(0, 1);
        ucCategory      =  ucCategory.toUpperCase() + category.substr(1);      
        
        // variables for the active category
        var active           = '';
        var ucActiveCategory = '';
        
        // if an active category is found relive it off its active state
        if($('#small-slider img[class=active]').length > 0){
            active                = $('#small-slider img[class=active]');
            var activeCategory    = $(active).attr('id');
            ucActiveCategory      = activeCategory.substr(0, 1);
            ucActiveCategory      = ucActiveCategory.toUpperCase() + activeCategory.substr(1); 
            $(active).removeClass('active').attr('src', site + 'templates/' + template + '/css/images/icon' + ucActiveCategory + '.gif');
        }       
        
        // now make the just clicked category acquire that active state
        $(this).addClass('active');
        $(this).attr('src', site + 'templates/' + template + '/css/images/icon' + ucCategory + 'Rollover.gif');
    });
    
    $('#small-slider ul li a img[class!=active]').mouseover(function(e){
        var category = e.target.id; // get recipe category
        // get the necessary variables for image path
        // change image
        var template  = $('input[name=template]').val();
        var site      = $('input[name=site]').val();
        
        var ucCategory  =  category.substr(0, 1);
        ucCategory      =  ucCategory.toUpperCase() + category.substr(1);
        
    // $(this).attr('src', site + 'templates/' + template + '/css/images/icon' + ucCategory + 'Rollover.gif');
     
    });
     
    $('#small-slider ul li a img[class!=active]').mouseleave(function(e){
        var category = e.target.id; // get recipe category
        // get the necessary variables for image path
        // change image
        var template  = $('input[name=template]').val();
        var site      = $('input[name=site]').val();
        
        var ucCategory  =  category.substr(0, 1);
        ucCategory      =  ucCategory.toUpperCase() + category.substr(1);
        
    //$(this).attr('src', site + 'templates/' + template + '/css/images/icon' + ucCategory + '.gif');
     
    });

    $('#small-slider').jcarousel({
        visible: 3,
        scroll: 1,
        wrap: 'circular'
    });
    /** END QUICK RECIPE SEARCH SLIDER */
    
    /** GLOBAL AND GENERAL SEARCH */
    $('#global_search').submit(function(){
        var keyword  = $('#global_search input[name=query]').val();
        
        if(keyword == '' || keyword == 'Search'){
            return false;
        }       
    });
    
    $('#go_btn').click(function(e){
        e.preventDefault();
        var keyword  = $('#keywordSearchForm input[name=searchword]').val();
        
        if(keyword == ''){
            return false;
        }        
        $('#keywordSearchForm').submit();    
    });
    /** END GLOBAL AND GENERAL SEARCH */

    /** POPUP IMPLEMENTATION (NYRO & COLORBOX) */
    $('.db_byemail').nyroModal({
        width:490
    });
    $('.meal_img a, .watch_video').nyroModal({
        width:684, 
        minHeight:543, 
        height: 543
    }); // for video popup
    $('.contact_us, .contact_the_chef').nyroModal({
        width:489, 
        height: 799
    }); // for video popup
    //$('.nyro_contact_us').nyroModal({width : 489, height : 799});

    $('.popup_sms, .popup_email, .popup_share, .popup_tag, .popup_note').nyroModal({
        width : 684
    }); // some popups
    
    //render all colorboxes
    $('a[class*="enter_comp"]').colorbox({
        height: 400,
        width: 490,
        href: hostname + '/templates/whats_for_dinner_sa/ajax/default-competition.html',
        onComplete: function() {
            $.colorbox.resize();
        },
        scrolling: false
    });
    
     //render all colorboxes
    $('a[class*="colorbox"]').colorbox({
        height: 799,
        width: 489,
        onComplete: function() {
                $.colorbox.resize();
            },
        scrolling: false
    });

    //render all colorboxes
    $('a[id^=winners]').colorbox({
        initialWidth: 50,
        initialHeight: 50,
        width: 820,      
        height: 1080,        
        onComplete: function() {
            $.colorbox.resize();
        },
        scrolling: false
    });

    //render all colorboxes
    $('a[id^=competition_1]').colorbox({
        initialWidth: 50,
        initialHeight: 50,
        width: 820,        
        href: hostname + '/templates/whats_for_dinner_sa/ajax/click-in-a-cook.php',
        onComplete: function() {
            $.colorbox.resize();
        },
        scrolling: false
    });

    //render all colorboxes
    $('a[id^=competition_2]').colorbox({
        initialWidth: 50,
        initialHeight: 50,
        width: 820,        
        href: hostname + '/templates/whats_for_dinner_sa/ajax/cook-in-a-bag.php',
        onComplete: function() {
            $.colorbox.resize();
        },
        scrolling: false
    });
   	 
    //render all colorboxes
    $('a[id^=competition_index]').colorbox({
        initialWidth: 50,
        initialHeight: 50,
        width: 820,      
        height: 1080,  
        href: hostname + '/templates/whats_for_dinner_sa/ajax/winners.php',
        onComplete: function() {
            $.colorbox.resize();
        },
        scrolling: false
    });   	 


    //competition_1
    

    $('.db_login, .db_signup, #popup-Email, #popup-Sms, #popup-Share').live('click', function(e) {
        e.preventDefault();
        $.nyroModalManual({
            url : $(this).attr('href'), 
            width : 684
        });
    });

    $('#enter_comp').live('click', function(e) {
        e.preventDefault();
        $.nyroModalManual({
            url : $(this).attr('href'), 
            width : 490
        });
    });

    $('.articles_send_to_friend').live('click', function(e) {
        e.preventDefault();
        $.nyroModalManual({
            url : $(this).attr('href'), 
            width : 684
        });
    });
    /** END POPUP IMPLEMENTATION (NYRO & COLORBOX) */

    /** TODAYS RECIPE TABS */
    $('.meals').jcarousel({
        visible: 1,
        scroll: 1,
        start: new Date().getDay(),
        initCallback: today_initCallback,
        animation: 700,
        easing: 'easeInOutQuart',
        buttonPrevHTML: null,
        buttonNextHTML: null
    });
    /** END TODAYS RECIPE TABS */

    /** MYCUPBOARD FORM BINDING */
    $('#add_ingri').click(function(e) {
        e.preventDefault();
        add_ingri();
    });
    /** END MYCUPBOARD FORM BINDING */

    /** MEASUREMENTS PAGE BINDING */
    $('.accordion-tab').click(function(event){
        var position =  $('.accordion-tab').position(); // get the position of the current target tab heading
        $('html, body').animate({
            scrollTop:position.top
            }, 'slow'); // move the page to the top position of the tab heading
    });

    $(".container").tabs(".container div.accordion-toggle", {
        tabs: 'h5', 
        effect: 'slide'
    });

    $('#unit_from').change(function(event){
        // need to check that the first option - which is blank does fire event
        if (event.target.value != '') {
            var option = event.target.value; // the value of the option choosen
            $.get('/index.php?option=com_measurement&task=getoption', {
                convertFrom: option, 
                action: "get"
            }, function(data){
                $('#unit_to').html('');	// clean out all the options
                $('#unit_to').html(data); // insert the options returned by server call
            }, "html");
        }
    });

    $('#convert').click(function(event){
        event.preventDefault();

        var unit_from  = $('#unit_from').val(); // unit to convert from
        var unit_to    = $('#unit_to').val(); // unit to convert to
        var amount     = $('#amount').val(); // amount to be used for the conversion

        if(amount == 'Enter amount'){
            alert('Please type in an amount for the conversion!');
            exit;
        }

        var regPattern = /^[0-9]*$/;
        if(!regPattern.test(amount)) {
            alert('Please only use numbers!');
            exit;
        }

        if(unit_from == ''){
            alert('Please select a unit to convert from!');
            exit;
        }

        if(unit_to == ''){
            alert('Please select a unit to convert from!');
            exit;
        }

        //else make ajax call for conversion
        $.get('/index.php?option=com_measurement&task=convert', {
            convertFrom: unit_from, 
            convertTo: unit_to, 
            amount: amount, 
            action: "get"
        }, function(data){
            $('#result').val(data);
        }, "html");
    });
    /** END MEASUREMENTS PAGE BINDING */
    

    $('.blink').live('focus', function() {
        if(this.value == this.title) {
            this.value = '';
        }
    }).live('blur', function() {
        if(this.value == '') {
            this.value = this.title;
        }
    });    
	
    $('.side-nav a').click(function() {
        if($(this).parent().find('ul').length) {
            $(this).parent().siblings('.open').removeClass('open').find('ul').slideUp();
            $(this).parent().toggleClass('open').find('ul').slideToggle();
            return false;
        }
    });

    $('.tt-link').live('mousemove', function(e) {
        var txt = $(this).find('img').attr('alt');
        var pos_l = e.pageX - 32;
        var pos_t = e.pageY - 52;
        $('.tooltip p').text(txt).parent().css({
            left: pos_l,
            top: pos_t
        });
    }).live('mouseleave', function() {
        $('.tooltip p').text('').parent().css({
            left: '-10000px',
            top: '-10000px'
        });
    });
	
    $('.tt-trigger').live('mouseover', function() {
        var txt = $(this).html();
        $('.tooltip2').find('p').html(txt);
        var pos_l = $(this).offset().left - Math.round($('.tooltip2').outerWidth()/2);
        var pos_t = $(this).offset().top - $('.tooltip2').outerHeight() - 8;
        $('.tooltip2').css({
            top: pos_t,
            left: pos_l
        });
    }).live('mouseleave', function() {
        tt_timeout = window.setTimeout(function() {
            $('.tooltip2').css({
                top: '-10000px',
                left: '-10000px'
            }).find('p').html('');
        }, 1000);
    });
	
    $('.tooltip2').live('mouseover', function() {
        window.clearTimeout(tt_timeout);
    }).live('mouseleave', function() {
        $('.tooltip2').css({
            top: '-10000px',
            left: '-10000px'
        }).find('p').html('');
    });
	
    $('.tooltip2 a').live('click', function() {
        var href = $(this).attr('href');
        if($(this).attr('href') != '#') {
            $.colorbox({
                href: href,
                initialWidth: 30,
                initialHeight: 30,
                onComplete: function() {
                    $.colorbox.resize();
                }
            });
        }
        return false;
    });
	
    $('.selectbox').selectbox();
	
    $('.custom-upload-container input').change(function() {
        $(this).parent().prev().val($(this).val());
    });
	
    $('.tab').click(function() {
        if($(this).hasClass('current') == false) {
            $(this).addClass('current').siblings('.current').removeClass('current');
            if($.browser.msie && $.browser.version < 8) {
                var tab = $(this).attr('hash');
            } else {
                var tab = $(this).attr('href');
            }
			
            $(tab).addClass('current').siblings('.current').removeClass('current');
        }
		
        return false;
    });
	
    if($('.tt-link').length) {
        $('body').append('<div class="tooltip"><p></p><span class="r"></span></div>');
    }
    if($('.tt-trigger').length) {
        $('body').append('<div class="tooltip2"><p></p><span class="arrow"></span></div>');
    }
	
    if($.browser.msie) {
        if($.browser.version < 8) {
            $('.tt-trigger').each(function() {
                $(this).css('top', '-5px');
            });
        }
        if($.browser.version == 6) {
            DD_belatedPNG.fix('#search .field, .meals li .overlay, .rating, .rating span, .tab, .recipe-rating span, .recipe-rating, .week-meals .day, .week-meals .icon, .meal-planner-top-box .left-box, .side-image');
        }
		
    }
});

$(document).ready(function() {

    /** COMMENTS START */
    setupCommentsForm2();

    //References
    var pages = $("#menu a");
    var loading = $("#loading");
    var content = $("#content");
    var contentabuse = $("#content .report_abuse");

    //show loading bar
    function showLoading(){
        $('#content .report_abuse').click(reportAbuse);
        $('#content .report_delete').click(reportDelete);
        $('#content .db_follow').nyroModal(); //comments popup
        $('#content .followuser').click(userFollow);
        
        //$('#content #db_follow').click(function(e) {
        //	e.preventDefault();
        //	$.nyroModalManual({
        //		url: 'demoSent.php'
        //      });
        //	return false;
        //});

        loading
        .css({
            visibility:"visible"
        })
        .css({
            opacity:"1"
        })
        .css({
            display:"block"
        })
    ;
    }

    //hide loading bar
    function hideLoading(){
        loading.fadeTo(10, 0);
        $('#content .report_abuse').click(reportAbuse);
        $('#content .report_delete').click(reportDelete);
        $('#content .db_follow').nyroModal(); //comments popup
        $('#content .followuser').click(userFollow);
    };

    //Manage click events
    pages.click(function(){
        //show the loading bar
        showLoading();

        //Load content
        var pageNum = this.id;
        var targetUrl = "index.php?option=com_comment&format=raw&layout=default_comments&page=" + pageNum + "&" + $("#myForm").serialize() + " #content";
        content.load(targetUrl, hideLoading);
    });

    var targetUrl = "/index.php?option=com_comment&format=raw&layout=default_comments&page=1&" + $("#myForm").serialize() + " #content";
    showLoading();
    content.load(targetUrl, hideLoading);
/** END COMMENTS START */
});

/** COMMENTS FUNCTIONS */
function setupCommentsForm2() {
    clearFormField('#commentsform');
    $(".submit").click(function() {
        var comment_comment = $("#comment_comment").val();
        var redirect 	    = $("#redirect").val();
        var target          = $("#target").val();
        var action          = $("#action").val();

        var dataString = 'comment_comment='+ comment_comment + '&redirect=' + redirect + '&target=' + target + '&action=' + action;

        if(comment_comment=='' || comment_comment=='Write a Comment') {
            //alert('Please Give Valide Details');
            $('#error').show();
            var comment = 'Please enter a comment.';
            $('#error').empty();
            $('#error').prepend(comment);
            $("#error").fadeOut(5000);
            $("#flash").css({
                display:"none"
            });
            return false;
        } else {
            $.ajax({
                type: "POST",
                url: "/index.php?option=com_comment&task=comment&format=raw",
                data: dataString,
                cache: false,
                success: function(html){
                    if (html=='false') {
                        //alert("ajax error");
                        var code = 'Please login or register to comment.';
                        $('#error').empty();
                        $('#error').prepend(code);
                        $('#error').css({
                            display:"block"
                        });
                        $("#error").fadeOut(5000);
                        $("#comm_status").css({
                            display:"none"
                        });
                    } else {
                        resetFields(); // reset form fields to their preset texts
                        $("#comm_status").css({
                            display:"block"
                        });						
                        $('#error').empty();
                        $("#error").css({
                            display:"none"
                        });
                        $("ul#posting").prepend(html);
                        $("ul#posting li:first").fadeIn("slow");
                        document.getElementById('comment_comment').value='';
                        $("#comm_status").fadeOut(5000);
                        $('#nocomment').remove();
                    }
                }
            });
            return false;
        }
    });
}

function resetFields(){
    //$('#commentsform #name').val('Name');
    $('#commentsform #comment_comment').val('Write a comment');
//$('#commentsform #email').val('Email');
//$('#commentsform #captcha').val('Verification Code');
}

function reportAbuse(e) {
    e.preventDefault();
    var commentId = $(this).attr('id');
    
    $.ajax({
        type: 'POST',
        url: '/includes/report_abuse.php',
        dataType: 'json',
        data: {
            commentId: commentId
        }
    });

    $(this).closest('.box').remove();

    //Load content
    var pageNum = this.id;
    var targetUrl = "index.php?option=com_comment&format=raw&layout=default_comments&page=" + pageNum + "&" + $("#myForm").serialize() + " #content";
    content.load(targetUrl, hideLoading);
}

function reportDelete(e) {
    e.preventDefault();
    var commentId = $(this).attr('id');

    $.ajax({
        type: 'POST',
        url: '/includes/report_delete.php',
        dataType: 'json',
        data: {
            commentId: commentId
        }
    });

    $(this).closest('.box').remove();
}

function userFollow(e) {
    e.preventDefault();

    // get rating function
    var idfollow = $('.followuser').attr('id');
    var userid = $('.followuser').attr('href').split("-")[1];

    $.ajax({
        type: "GET",
        url: "/includes/do_follow.php",
        data: "do=getfollow&id="+idfollow+"&user="+userid,
        cache: false,
        async: false,
        success: function(result) {
            // apply follow element
            $("#content").refresh();
        },
        error: function(result) {
            alert("some error occured, please try again later");
        }
    });
}

var formDetails = new Array();
function clearFormField(form){
    var formName = $(form).attr('id');
    formDetails[formName] = new Array();

    $(form).find('input[type=text],textarea').each(function() {
        var formName = $(this).closest('form').attr('id');
        var fieldName = $(this).attr('id');
        //save original input (if any)
        formDetails[formName][fieldName] = $(this).attr('value');

        $(this).focus(function() {
            var formName = $(this).closest('form').attr('id');
            var fieldName = $(this).attr('id');
            if($(this).val() == formDetails[formName][fieldName]) {
                $(this).val('');
            }
        }).blur(function() {
            if($(this).val() == '') {
                var formName = $(this).closest('form').attr('id');
                var fieldName = $(this).attr('id');
                $(this).val(formDetails[formName][fieldName]);
            }
        });
    });
}

function  refresh() {
    var sURL = unescape(window.location.pathname);
    window.location.href = sURL;
    clearTimeout();
}
/** END COMMENTS FUNCTIONS */

/** MYCUPBOARD FUNCTIONS */
var ingredients = new Array();

function get_ingredients() {
    ingredients = new Array(); // clear array from any previous data
    // check for the nos of ingredients on the page with the id prefixed with 'ingri_'
    if ($('input[id^=ingri_]').length > 0){
        $('input[id^=ingri_]').each( function(i) {
            var id  = $(this).attr('id');
            id = id.substring(6); // stip out the 'ingri' prefix identifier
            ingredients[i] = id; // add the ids to array
        });
    }
}

// process to delete the item from in ingredient list
function del_ingri(ingri){ 
    // remove the the ingredient deleted from the ingredient array
    ingredients.splice(ingri, 1); 
   
    $('#ingri_' + ingri + ', .ingri_' + ingri).remove(); // remove the checkbox
   
    if (ingredients != '') {
        search_recipes(ingredients);
    } else {
        $('#pageTitle').hide();
        $('#recipe_ajax_cont').html('');
    }
}

function add_ingri(search){ 
    get_ingredients(); // get all the ingredients
    if (search == undefined) {
        // if there isnt a search parameter passed which means the function
        // was triggered by the onclick event run block
        search_value = $('#search_q').val(); // get the search query
    } else {
        // this is for the manual triggering from the home page
        // search will be a value passed
        search_value  = search;
    }

    search_value = search_value.toLowerCase(search_value); // change search value to lowercase
    var find     = $('#'+ 'ingri_' + search_value).length; // check if the ingredient has already been added to page   
    
   
    //only for when it is based on click event
    if (search == undefined) {       
        ingredients[ingredients.length] = search_value; // add search value to the array
    }
    
    // this is to cater for ingredients coming from index page, make the global ingredient array be set to the 
    if(ingredients.length == 0){
        ingredients[0] = '';
        ingredients[0] = search_value;
    }
    
    //if request is triggered by the onclick event on the Add button on the mycupboard page
    if(search_value != '' && find == 0 && search_value != 'Enter an ingredient') {
        // add found ingredients to page
        $('.filter_cont').prepend('<div class="found" id="ingri_' + search_value + '"><a href="#" onclick="del_ingri(\''+ search_value + '\'); return false"><img width="10" height="12" src="/templates/whats_for_dinner_sa/css/images/close.gif"></a><span>' + search_value + '</span></div><input type="hidden" id="ingri_' + search_value + '" value="' + search_value + '" />');
        search_recipes(ingredients); // make a post request to server side
    }

}

// search for recipes on server side using ajax post request
function search_recipes(ingredients){
    // add new ingredient to list of ingredients
    $.post('index.php?option=com_recipe&view=mycupboard&format=ingri_ajax', {
        'add_ingri': ingredients
    }, function(data) {
        $('.filter_cont').css('border-bottom', 'none');
        $('#recipe_ajax_cont').html('').html(data);	// get all recipes returned and populate to div container
        $('#search_q').val(''); // clean out the search input field
    });
}
/** END MYCUPBOARD FUNCTIONS */

/** CALLBACK FUNCTION FOR THE DAILY RECIPE SLIDER */
function today_initCallback(carousel) {
    $('.weekdays a').bind('click', function() {
        if($('.meals').is(':animated') == false) {
            $(this).parent().addClass('current').siblings('.current').removeClass('current');
            carousel.scroll($.jcarousel.intval($(this).parent().index()+1));
        }
        return false;
    });
}
/** END CALLBACK FUNCTION FOR THE DAILY RECIPE SLIDER */

//fires the competition popup manually
var hostname  = 'http://' + window.location.hostname;

function competition(){
    /*
    $.colorbox({
        href: hostname + '/templates/whats_for_dinner_sa/ajax/feb2012-bimonthly/index.php',
        scrolling: false,
        height: 400,
        width: 490,
        initialWidth: 50,
        initialHeight: 740,
        onClosed: function(){
            $('.FB_UI_Dialog').remove(); // remove the the fb dialog if it open 
        }
    });*/
    
    $.fancybox({
        href: hostname + '/templates/whats_for_dinner_sa/ajax/feb2012-bimonthly/index.php',
        type:'iframe', 
        width: 947, 
        height: 700,
        hideOnOverlayClick: false,
        onComplete: function(){
                $('#fancybox-content').css('height', '740px').css('background', 'none').css('border-width', 0);
                $('#fancybox-outer').css('background', 'transparent');
                $('.fancybox-bg').remove();
                $('#fancybox-close')
                .css('top','49px')
                .css('right','23px')
                .css('width','14px')
                .css('height','14px')
                .css('background', 'url(/templates/whats_for_dinner_sa/ajax/feb2012-bimonthly/img/fancy-close.png)');                
        },
        padding: 0
        
    });
}

// Closes the lightbox 
function closeColorBox(){
    $.colorbox.close();
}

function welcome(){
    $.colorbox({
        href: hostname + '/templates/whats_for_dinner_sa/ajax/welcome.html',
        scrolling: false,
        height: 650,
        initialWidth: 50,
        initialHeight: 50,
        onClosed: function(){}
    });
}

$(document).bind('cbox_complete', function() {

    if($('.pop-tabs').length) {

        $('.pop-tabs .tab-links li:first, .pop-tabs .tab-entry:first').addClass('current');

    }


    if($('#cboxLoadedContent .media-popup').length) {

        if($('.popup-gallery').length) {

            $('.popup-gallery .large').append('<ul />');



            var items_length = $('.popup-gallery .small li').length;

            for(i=1;i<=items_length;i++) {

                var $item = $('.popup-gallery .small li').eq(i-1);

                var img_src = $item.find('a').attr('href');

                $('.popup-gallery .large ul').append('<li><img src="' + img_src + '" /></li>');

                $item.find('a').attr('href', '#');

            }



            $('.popup-gallery .large ul').jcarousel({

                visible: 1,

                scroll: 1,

                animation: 700,

                easing: 'easeInOutQuart',

                wrap: 'both',

                initCallback: function(carousel) {

						

                },

                itemFirstInCallback: function(carousel,item,idx,state) {

                    var $item = $('.popup-gallery .small li').eq(idx-1);

                    var img_desc = $item.find('.notext').text();

                    $('.popup-gallery .text p').text(img_desc);

                    $item.addClass('current').siblings('.current').removeClass('current');



                    if(idx > 5) {

                        $('.popup-gallery .small ul').data('jcarousel').scroll(idx);

                    } else {

                        if($('.popup-gallery .small ul').data('jcarousel') != undefined) {

                            $('.popup-gallery .small ul').data('jcarousel').scroll($.jcarousel.intval(1));

                        }

                    }

                }

            });



            $('.popup-gallery .small ul').jcarousel({

                scroll: 1,

                visible: 5,

                wrap: 'both',

                itemFallbackDimension: 80,

                initCallback: function(carousel) {

                    if($('.c-clicked').length) {

                        var c_idx = $('.c-clicked').index();

                        $('.c-clicked').removeClass('c-clicked');

                        $('.popup-gallery .large ul').data('jcarousel').scroll($.jcarousel.intval(c_idx+1));

                    }



                    $('.popup-gallery .small a').live('click', function() {

                        var t_idx = $(this).parent().index();

                        $('.popup-gallery .large ul').data('jcarousel').scroll($.jcarousel.intval(t_idx+1));

                        return false;

                    });

                }

            });

        }

    }

});



/***********************************************************************/
/* personal meal planner 											   */
/***********************************************************************/


$(function() {
	
    $(".mini-tabs").each(function() {
        var $t = $(this);
        var $c = $(this).siblings(".mini-tabs-content");
        $(".mini-tab", $c).hide().eq(0).show();
        $(this).find("a").removeClass("active").eq(0).addClass('active');
        $(this).find("a").click(function() {
            var href = $( $(this).attr("href") );

            href.siblings().hide();
            href.show();
			
            $("a", $t).removeClass("active");
            $(this).addClass("active");
			
            return false;
        });
    });
	
    $(".featured-tabs ul li a").click(function() {
        if( $(this).parent().index() == 0 )
            $("#featured .shell").removeClass("active-shell");
        else
            $("#featured .shell").addClass("active-shell");
			
        return false;
    });


    if($('.tab-links').length) {
        $('.tab-links li:first, .tab-entries .tab-entry:first').addClass('current');
    }

    $('.tab-links a').live('click', function() {
        $(this).parent().addClass('current').siblings('.current').removeClass('current');
        var targ = $(this).attr('href');
        var doc_location = document.location;
        targ = targ.toString().replace(doc_location, '');
        $(targ).addClass('current').siblings('.current').removeClass('current');
        if($('#colorbox').is(':visible')) {
            $.colorbox.resize();
        }
        return false;
    });
	
    $('.pop-step2 .p-weekdays li, .pop-step6 .row p .icon').live('click', function() {			
        $(this).toggleClass('active');	
		
        value = $(this).attr("class");
        //mon
        if (value == 'mon active') {
            $('input[name$="mon"]').val('1');
        } else if (value == 'mon') {
            $('input[name$="mon"]').val('0');
        }
        //tue
        if (value == 'tue active') {
            $('input[name$="tue"]').val('1');
        } else if (value == 'tue') {
            $('input[name$="tue"]').val('0');
        }
        //wed
        if (value == 'wed active') {
            $('input[name$="wed"]').val('1');
        } else if (value == 'wed') {
            $('input[name$="wed"]').val('0');
        }	
        //thu
        if (value == 'thu active') {
            $('input[name$="thu"]').val('1');
        } else if (value == 'thu') {
            $('input[name$="thu"]').val('0');
        }
        //fri
        if (value == 'fri active') {
            $('input[name$="fri"]').val('1');
        } else if (value == 'fri') {
            $('input[name$="fri"]').val('0');
        }
    });	

    $('.pop-step4 .row li').live('click', function() {
        $(this).toggleClass('active');
        value = $(this).attr("class");
		
        //values for the  preferences
        if (value == 'milk active') {
            $('input[name$="milk"]').val('1');
        } else if (value == 'milk') {
            $('input[name$="milk"]').val('0');
        }			
        if (value == 'eggs active') {
            $('input[name$="eggs"]').val('1');
        } else if (value == 'eggs') {
            $('input[name$="eggs"]').val('0');
        }		
        if (value == 'nuts active') {
            $('input[name$="nuts"]').val('1');
        } else if (value == 'nuts') {
            $('input[name$="nuts"]').val('0');
        }		
        if (value == 'fish active') {
            $('input[name$="fish"]').val('1');
        } else if (value == 'fish') {
            $('input[name$="fish"]').val('0');
        }		
        if (value == 'wheat active') {
            $('input[name$="wheat"]').val('1');
        } else if (value == 'wheat') {
            $('input[name$="wheat"]').val('0');
        }		
        //field 2
        if (value == 'pasta active') {
            $('input[name$="pasta"]').val('1');
        } else if (value == 'pasta') {
            $('input[name$="pasta"]').val('0');
        }		
        if (value == 'poultry active') {
            $('input[name$="poultry"]').val('1');
        } else if (value == 'poultry') {
            $('input[name$="poultry"]').val('0');
        }		
        if (value == 'meat active') {
            $('input[name$="meat"]').val('1');
        } else if (value == 'meat') {
            $('input[name$="meat"]').val('0');
        }		
        if (value == 'veg active') {
            $('input[name$="veg"]').val('1');
        } else if (value == 'veg') {
            $('input[name$="veg"]').val('0');
        }		
        if (value == 'seafood active') {
            $('input[name$="seafood"]').val('1');
        } else if (value == 'seafood') {
            $('input[name$="seafood"]').val('0');
        }		

        if (value == 'snack active') {
            $('input[name$="snack"]').val('1');
        } else if (value == 'snack') {
            $('input[name$="snack"]').val('0');
        }		
        if (value == 'special active') {
            $('input[name$="special"]').val('1');
        } else if (value == 'special') {
            $('input[name$="special"]').val('0');
        }		
        if (value == 'crowd active') {
            $('input[name$="crowd"]').val('1');
        } else if (value == 'crowd') {
            $('input[name$="crowd"]').val('0');
        }		
        if (value == 'braai active') {
            $('input[name$="braai"]').val('1');
        } else if (value == 'braai') {
            $('input[name$="braai"]').val('0');
        }		
        if (value == 'comfort active') {
            $('input[name$="comfort"]').val('1');
        } else if (value == 'comfort') {
            $('input[name$="comfort"]').val('0');
        }		
        if (value == 'quick active') {
            $('input[name$="quick"]').val('1');
        } else if (value == 'quick') {
            $('input[name$="quick"]').val('0');
        }		
				
    });

    $('.pop-step3 .active .field').live('keyup', function() {
        var leng = parseInt($(this).val());
        $(this).parents('.active:eq(0)').find('.people').html('');

        for(i=0;i<leng;i++) {
            $(this).parents('.active:eq(0)').find('.people').append('<span />');
        }
    });

    $('.pop-step5 .p-weekdays .active').live('mouseenter', function() {
        $(this).find('.tooltip').show();
    }).live('mouseleave', function() {
        $(this).find('.tooltip').hide();
    });

    $('.pop-step1 .btn-view, .pop-step5 .btn-view').live('click', function() {
        $('.feat-thumbs').fadeOut(400, function() {
            $('.pop-tabs').fadeIn(400, function() {
                $.colorbox.resize();
            });
            $('.btn-back').fadeIn(400);
        });
        $(this).fadeOut(400).next().fadeOut(400);
        return false;
    });

    $('.pop-step1 .btn-back, .pop-step5 .btn-back').live('click', function() {
        $('.pop-tabs').fadeOut(400, function() {
            $('.feat-thumbs').fadeIn(400, function() {
                $.colorbox.resize();
            });
            $('.btn-view').fadeIn(400).next().fadeIn(400);
        });
        $(this).fadeOut(400);
        return false;
    });
	
	
    $('.planner-popup .btn-view, .featured-recipe .corner').live('click', function() {
        $('.feat-thumbs').fadeOut(400, function() {
            $('.pop-tabs').fadeIn(400, function() {
                $.colorbox.resize();
            });
            $('.btn-back').fadeIn(400);
        });
        $.colorbox.resize();
        $('.planner-popup .btn-view').fadeOut(400).next().fadeOut(400);
        return false;
    });

    $('.planner-popup .btn-back').live('click', function() {
        $('.pop-tabs').fadeOut(400, function() {
            $('.feat-thumbs').fadeIn(400, function() {
                $.colorbox.resize();
            });
            $('.btn-view').fadeIn(400).next().fadeIn(400);
        });
        $.colorbox.resize();
        $(this).fadeOut(400);
        return false;
    });
	
    $.colorbox.resize();
			
});


$(document).bind('cbox_complete', function() {
    if($('.pop-tabs').length) {
        $('.pop-tabs .tab-links li:first, .pop-tabs .tab-entry:first').addClass('current');
    }

    if($('.pop-step3').length) {
        $('.pop-step3 .p-weekdays .active').each(function() {
            $(this).append('<div class="people" />')
            var leng = parseInt($(this).find('.field').val());
            for(i=0;i<leng;i++) {
                $(this).find('.people').append('<span />');
            }
        });
    }

    if($('.pop-step5').length) {
        $('.pop-step5 .p-weekdays .active').each(function() {
            var tt_wid = $(this).find('.tooltip').width() + 10;
            var tt_l = '-' + (tt_wid/2) + 'px';
            $(this).find('.tooltip').css('margin-left', tt_l).hide();
        });
    }

    if($('#cboxLoadedContent .media-popup').length) {
        if($('.popup-gallery').length) {
            $('.popup-gallery .large').append('<ul />');

            var items_length = $('.popup-gallery .small li').length;
            for(i=1;i<=items_length;i++) {
                var $item = $('.popup-gallery .small li').eq(i-1);
                var img_src = $item.find('a').attr('href');
                $('.popup-gallery .large ul').append('<li><img src="' + img_src + '" /></li>');
                $item.find('a').attr('href', '#');
            }

            $('.popup-gallery .large ul').jcarousel({
                visible: 1,
                scroll: 1,
                animation: 700,
                easing: 'easeInOutQuart',
                wrap: 'both',
                initCallback: function(carousel) {
						
                },
                itemFirstInCallback: function(carousel,item,idx,state) {
                    var $item = $('.popup-gallery .small li').eq(idx-1);
                    var img_desc = $item.find('.notext').text();
                    $('.popup-gallery .text p').text(img_desc);
                    $item.addClass('current').siblings('.current').removeClass('current');

                    if(idx > 5) {
                        $('.popup-gallery .small ul').data('jcarousel').scroll(idx);
                    } else {
                        if($('.popup-gallery .small ul').data('jcarousel') != undefined) {
                            $('.popup-gallery .small ul').data('jcarousel').scroll($.jcarousel.intval(1));
                        }
                    }
                }
            });

            $('.popup-gallery .small ul').jcarousel({
                scroll: 1,
                visible: 5,
                wrap: 'both',
                itemFallbackDimension: 80,
                initCallback: function(carousel) {
                    if($('.c-clicked').length) {
                        var c_idx = $('.c-clicked').index();
                        $('.c-clicked').removeClass('c-clicked');
                        $('.popup-gallery .large ul').data('jcarousel').scroll($.jcarousel.intval(c_idx+1));
                    }

                    $('.popup-gallery .small a').live('click', function() {
                        var t_idx = $(this).parent().index();
                        $('.popup-gallery .large ul').data('jcarousel').scroll($.jcarousel.intval(t_idx+1));
                        return false;
                    });
                }
            });
        }
    }
		
		
//$(".dragImage").draggable({ revert: 'invalid'});
//$('#inventory').droppable();
//$(".active").droppable({ accept: '.dragImage'})
	
	
//$(".dragImage").draggable({ revert: 'invalid'});
//$('#inventory').droppable();
//$(".active").droppable({ accept: '.dragImage'})
//$('#helmet_spot').droppable({ accept: '.helmets'});
//$('.active,#inventory').bind('drop', function(ev,ui) { itemInSpot(ui.draggable,this); });	
	
//function itemInSpot(drag_item,spot) //.....
//{

});

/***********************************************************************/
/* END - personal meal planner 										   */
/***********************************************************************/



