$(document).ready(function() {
	
});

function initPopup(){
	// This check is used by the demo to allow you to remove the cookie. Do not use in production code.
	if (HasAlreadyReceivedPopup("testpopup"))
		$("#note").show().click(function () { 
			document.cookie = name + "testpopup=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT"; location.reload(true); 
		});

	CreatePopup("../../popup/popup.html", 200, 1500, "testpopup", 5); 
}

function initBuddyRequest(clsShow, clsHide){
	$('div.'+clsHide).hide();
	$('div.panel div.inner ul li a.button-buddies').show();
	$('div.panel div.inner ul li.' + clsShow + ' a.button-buddies').click(function(e){
		e.preventDefault();
		$('.' + clsHide, $(this).parents('li:has(li)')).show();
		$(this).parent().hide();		 
	});
	
	$('.' + clsHide + ' a.cancel').show().click(function(e){
		e.preventDefault();
		$(this).parent().hide();
		$('.'+clsShow, $(this).parents('li')).show();
	});
	$('.panel-send textarea').click(function(e){
		e.preventDefault();
		$(e.target).val('');
	});
}

function initForum(){
	$("ul.forum-content li").css('cursor', 'pointer');
	$("ul.forum-content li").click(function(event){
		if(!$(event.target).is('input.star')){
			var x = $(this).contents("div").find("a").attr("href");
			window.location.href = x;
		}
	})
}


// Fading effects for questions
function initQuestionToggle(isCheckbox, onCheck) {

    var fadeSpeed = 0;

    // Set up checkboxes
    $(".personalplan div#questions").addClass("js");
    $("div#questions ol li > p").append("<span class=\"checkbox\"></span>");
    $(".personalplan div#questions .form ol li").append("<div class=\"underlay\"></div>").hover(
		function() { // mouseover
		    // $(this).addClass("hover").children("div.underlay").fadeIn(fadeSpeed);
		    var underlayHeight = $(this).height();
		    $(this).addClass("hover").children("div.underlay").height(underlayHeight).show();
		},
		function() { // mouseout
		    var me = $(this);
		    if ($(this).hasClass("checked")) {
		    } else {
		        $(me).removeClass("hover").children("div.underlay").hide();
		    }
		}
	);

    $.fn.fadeInOut = function() {
        if (!jQuery.browser.msie) {
            $(this).fadeOut(100, function() { $(this).fadeIn(100) })
        }
    }

    $(".personalplan div#questions .form ol li > p").each(function() {
        if ($(this).children("input").attr('checked')) {
            $(this).parent("li").addClass("hover").addClass("checked").children("div.underlay").show().addClass("active");
        }
    });

    if (isCheckbox) {
        $(".personalplan div#questions .form ol li > p").toggle( // Click events
		    function(event) {
		        $(this).parent("li").addClass("checked").children("div.underlay").addClass("active");
		        $(this).parent("li").children("p").children("span.checkbox").fadeInOut();
		        $(this).children("input").attr('checked', true);
		        if (typeof (onCheck) == "function") { onCheck($(this).children("input")); }
		        return false;
		    },
		    function(event) {
		        $(this).parent("li").removeClass("checked").children("div.underlay").addClass("active");
		        $(this).parent("li").children("p").children("span.checkbox").fadeInOut();
		        $(this).children("input").attr('checked', false);
		        if (typeof (onCheck) == "function") { onCheck($(this).children("input")); }
		        return false;
		    }
	    );
    } else {
        $(".personalplan div#questions .form ol li > p").bind('click', // Click events
		    function(event) {
		        $("li").removeClass("hover").removeClass("checked").children("div.underlay").hide();
		        $(this).parent("li").addClass("hover").addClass("checked").children("div.underlay").show().addClass("active");
		        $(this).children("input").attr('checked', true);
		        if (typeof (onCheck) == "function") { onCheck($(this).children("input")); }
		        return false;
		    }
        );
    }
}

function initCustomize(){
 	$("#custom-open").hide();
	$("#custom-button a").unbind('click.custombutton').bind('click.custombutton',function() {
	
	        if ($(this).parents('#panel-customize-plan').next('div#custom-open').hasClass("open")) {
	            $(this).parent().removeClass('subtract').addClass('add');
	            $(this).parents('#panel-customize-plan').next('div#custom-open').removeClass("open").slideUp("slow");
	        } else {
	            $(this).parent().removeClass('add').addClass('subtract');
	            $(this).parents('#panel-customize-plan').next('div#custom-open').slideDown("slow").addClass("open");
	        }
	
	        return false;
	    });
}


var initialValue = "";

function initPlannerDay() {
    $("div.meal_description, div.add-event-form").hide();
    $(".plan ul li div.meal").unbind('click.meals').bind('click.meals',function() {

        if ($(this).parent().children("div.meal_description").hasClass("open")) {
            $(this).parent().children("div.meal_description").removeClass("open").slideUp("slow");
            $(this).removeClass('open');
        } else {

            $("div.meal_description").slideUp("slow").removeClass("open").parent().children("div.meal").removeClass("open");
            $(this).parent().children("div.meal_description").slideDown("slow").addClass("open");
            $(this).addClass('open');
        }
        return false;
    });

    $("#add-event a").unbind('click.addevent').bind('click.addevent',function() {

        $("#add-event").hide();
        $("div.add-event-form").slideDown("slow");
        return false;
    });

    $("div.add-event-form a.subtract").unbind('click.subtractevent').bind('click.subtractevent', function() {
        $("div.add-event-form").slideUp("slow", function() {
            $("#add-event").show();
        });
        return false;
    });

    initCustomize();

    $(".plan ul li").hover(
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);

    // If text box is blank then populate with "Type in your own meal..."
    if ($('.change-meals .input-left').val() == "") $('.change-meals .input-left').val(initialValue);
    $('.change-meals .input-left').bind("focus", focusCustomMealText);
    $('.change-meals .input-left').bind("blur", blurCustomMealText);
}

function focusCustomMealText() {
    if ($(this).val() == initialValue) $(this).val("");
}

function blurCustomMealText() {
    if ($(this).val() == "") $(this).val(initialValue);
}

function initPlannerWeek() {
    $("#custom-open").hide();
    $("#custom-button a").unbind('click.custombutton').bind('click.custombutton',function() {

        if ($(this).parents('#panel-customize-plan').next('div#custom-open').hasClass("open")) {
            $(this).parent().removeClass('subtract').addClass('add');
            $(this).parents('#panel-customize-plan').next('div#custom-open').removeClass("open").slideUp("slow");
        } else {
            $(this).parent().removeClass('add').addClass('subtract');
            $(this).parents('#panel-customize-plan').next('div#custom-open').slideDown("slow").addClass("open");
        }

        return false;
    });

}

function initDashboard(inEditMode) {
    if (!inEditMode) {
        $('#panel-settings > a').remove();
        $('#panel-settings').prepend('<a href="#edit" name="edit" class="icon-add">' + label_edit + '</a>');
            
        $('fieldset li input[type="text"]').each(function() {
            if($(this).parent().children('.settings_field').size() == 0)
                $(this).parent().append('<span class="settings_field">' + $(this).next("input[type='hidden']").val() + '</span>');
            else
                $(this).parent().children('.settings_field').css('display','inline').text($(this).next("input[type='hidden']").val());
            $(this).hide();
        });
        $('fieldset li input[type="checkbox"]').each(function() {
            if($(this).parent().children('.settings_field').size() == 0)
                $(this).parent().append('<span class="settings_field">' + $(this).next("input[type='hidden']").val() + '</span>');
            else
                $(this).parent().children('.settings_field').css('display','inline').text($(this).next("input[type='hidden']").val());
            $(this).hide();
        });
        $('fieldset li select').each(function() {
            if($(this).parent().children('.settings_field').size() == 0)
                $(this).parent().append('<span class="settings_field">' + $(this).next("input[type='hidden']").val() + '</span>');
            else
                $(this).parent().children('.settings_field').css('display','inline').text($(this).next("input[type='hidden']").val());
            $(this).hide();
        });
        $('fieldset input[type="file"]').parent().hide();
        $('input.save-button').parent().hide();
        $('div.bmi-check').hide();
    } else {
        $('#panel-settings > a').remove();
        $('#panel-settings').prepend('<a href="#edit" name="edit" class="subtract">' + label_close + '</a>');            
        $('fieldset li input[type="text"]').each(function() {
            if($(this).parent().children('.settings_field').size() == 0)
                $(this).parent().append('<span style="display:none;" class="settings_field">' + $(this).next("input[type='hidden']").val() + '</span>');
            else
                $(this).parent().children('.settings_field').css('display','none').text($(this).next("input[type='hidden']").val());
        });
        $('fieldset li input[type="checkbox"]').each(function() {
            if($(this).parent().children('.settings_field').size() == 0)
                $(this).parent().append('<span style="display:none;" class="settings_field">' + $(this).next("input[type='hidden']").val() + '</span>');
            else
                $(this).parent().children('.settings_field').css('display','none').text($(this).next("input[type='hidden']").val());
        });
        $('fieldset li select').each(function() {
            if($(this).parent().children('.settings_field').size() == 0)
                $(this).parent().append('<span style="display:none;" class="settings_field">' + $(this).next("input[type='hidden']").val() + '</span>');
            else
                $(this).parent().children('.settings_field').css('display','none').text($(this).next("input[type='hidden']").val());
        });        
    }
    $('#panel-settings > a').unbind('click').bind('click', function(e) {
        if ($(this).hasClass("icon-add")) {
            $(this).text(label_close);
            $(this).attr('class', 'subtract');
            showHideSettingsEditMode(true);
        } else {
            $(this).text(label_edit);
            $(this).attr('class', 'icon-add');
            showHideSettingsEditMode(false);
        }
    });    
}

function showHideSettingsEditMode(show) {
    if (show) {
        $('#panel-settings span.settings_field').hide();
        $('fieldset li input[type="text"]').show();
        $('fieldset li input[type="checkbox"]').show();
        $('fieldset li select').show();
        $('#panel-settings a.icon-add').hide();
        $('fieldset input[type="file"]').parent().show();
        $('input.save-button').parent().show();
    } else {
        $('#panel-settings span.settings_field').show();
        // Close link works like a cancel button so revert all inputs to their original states
        $('fieldset li input[type="text"]').each(function() {
            $(this).val($(this).next("input[type='hidden']").val());
            $(this).hide();
        });
        $('fieldset li input[type="checkbox"]').each(function() {
            if ($(this).next("input[type='hidden']").val() == label_yes) {
                $(this).attr('checked', 'true');
            } else {
                $(this).attr('checked', 'false');
            }
            $(this).hide();
        });
        $('fieldset li select').each(function() {
            var selectedText = $(this).next("input[type='hidden']").val();
            $(this).find("option").each(function() {
                $(this).attr("selected", "selected");
            });
            $(this).hide();
        });
        $('#panel-settings a.icon-add').show();
        $('fieldset input[type="file"]').parent().hide();
        $('input.save-button').parent().hide();
        $('div.bmi-check').hide();  
        $('.error').hide();  
    }
}

function initShoppingList() {
        
    $(".shoppingListMealHeader").unbind('click.custombutton').bind('click.custombutton',function() {
        var slider = $(this).next("div");
        if(!slider.hasClass("open"))
        {
            $(".open").removeClass("open").slideUp("fast");
            slider.addClass("open").slideDown("slow");
        }
        else
            slider.removeClass("open").slideUp("fast");
            
        return false;
    });
    
    $(".remove a").unbind("click.removeItem").bind("click.removeItem",function() {
        $(this).parent().parent().hide();
        var rowIndex = 0;
        $('tr').removeClass('odd');
        $('tr').each(function(){
            if($(this).css('display') != 'none')
                if(rowIndex++%2 != 0)
                    $(this).addClass('odd');
        });
        return false;
    });
}

function initShareFeelings(clientId,feelingFormatString,event) {
    $(".no-js-submit-mood").css('display','none');
    $('#'+clientId).unbind('change').bind('change',function(){
        var location = String.format(feelingFormatString,$(this).children('option:selected').text());
        var code = location + event + 's.prop9=\"' + s.prop7 + ':cp-feeling\";';
        linkCode(this,'prop9,eVar19','',code,'o','Feeling_Changed');
    });
}

function validateRadioButtons(source, args) {
    var numberChecked = 0;
    $("#" + source.id).parent().find("p input[type='radio']").each(function() {
        if ($(this).attr("checked")) {
            numberChecked++;
        }
    });
    if (numberChecked == 0) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}

var initFormPasswordLabel = "";

function initFormLabels() {
	
	$("p#pw").append("<input type=\"text\" name=\"input-password\" value=\"\" id=\"input-mask\" class=\"input-text\" />")
	$("div#top-forms input[type='password']").hide();

	$("div#top-forms .input-email").val($(".input-email").prev("label").text());
	initFormPasswordLabel = $("#input-mask").prev("input").prev("label").text();
	$("div#top-forms #input-mask").val(initFormPasswordLabel);
	$("div#top-forms .input-search").val($(".input-search").prev("label").text());

    $("div#top-forms input[type='text']").focus(function() {
        if ($(this).val() == $(this).prev("label").text()) {
            $(this).val("").css("color", "#000000")
        }
        else if ($(this).val() == initFormPasswordLabel)
		{
			$(this).hide();
			$("div#top-forms input[type='password']").show().focus().css("color", "#000000");
		}
    },
	$("div#top-forms input[type='text']").blur(function() {
	    if ($(this).val() == "") {		
	        $(this).val($(this).prev("label").text()).css("color", "#cccccc")
	    } 
	}),
	$("div#top-forms input[type='password']").blur(function() {
		if ($(this).val() == "") {		
			$(this).hide();
			$("input#input-mask").show();
	    } 
	})	
	)
}

function initTooltips()
{
// Create the tooltips only on document load
$(document).ready(function() 
{
	$.fn.qtip.styles.mystyle = { // Last part is the name of the style
	   width: 200,
	   background: '#A2D959',
	   color: 'black',
	   textAlign: 'center',
       size: {
            x: 200,
            y : 80
       },
	   border: {
		  width: 7,
		  radius: 5,
		  color: '#A2D959'
	   },
	   tip: 'bottomLeft',
	   name: 'dark' // Inherit the rest of the attributes from the preset dark style
	}
   // By suppling no content attribute, the library uses each elements title attribute by default
   $('#plan-shopping-list div[id][title]').qtip({
      content: {
         text: false // Use each elements title attribute
      },
      position: {
		corner: {
			target: 'topRight',
			tooltip: 'bottomLeft'
		}
      },
      style: 'mystyle' // Give it some style
   });
 
    // Notice the use of the each() method to acquire access to each elements attributes
   $('#plan-shopping-list div[tooltip]').each(function()
   {
      $(this).qtip({
         content: $(this).attr('tooltip'), // Use the tooltip attribute of the element for the content
         style: 'cream' // Give it a crea mstyle to make it stand out
      });
   });
});
}

function TescoSetValues(source, args)
{
    var objForm = document.form1; 
    var errorCount = 0; 

    var isChecked = false; 
    var i = 1;
	
    ctrlName = 'ctl00_ctl00_phBase_ctlMain_ctl00_' + source + '_ctl0' + i + '_chkInclude';
    var curItem = DOMCall(ctrlName);
    //start looping through the Repeater
    while (curItem != null)
    {
        //using the != null check should keep it from getting locked up
        if(args == 'all') { curItem.checked = true; }
        if(args == 'none') { curItem.checked = false; }
        isChecked = true;

        //now check to see the value of i, if it's equal or greater than 10 we need to change how we look for the next control
        if(i >= 10)
        {
            ctrlName = 'ctl00_ctl00_phBase_ctlMain_ctl00_' + source + '_ctl' + i + '_chkInclude';
        }
        else    
        {
			ctrlName = 'ctl00_ctl00_phBase_ctlMain_ctl00_' + source + '_ctl0' + i + '_chkInclude';
        }      
                      
        curItem = DOMCall(ctrlName);  
        i += 1           
    }
    return isChecked;
}

//function to use whatever DOM Object
//the users browser has
function DOMCall(name) 
{
  //Checks the DOM features available
   if (document.layers) //checks document.layers
        return document.layers[name];
   else if (document.all) //checks document.all
        return document.all[name];
   else if (document.getElementById) //checks getElementById
        return document.getElementById(name);
}

function GetOmniturePageName()
{
	try
	{
		return s.pageName;
	}
	catch(e)
	{
		return document.title;
	}
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)