function bindDropDownPanel(dropDownSelector, panelSelector, imagePath) {
    var checkedImage = imagePath;
    var unCheckedImage = imagePath.replace("_on.png", ".png");
    $(dropDownSelector).hover(
        function() {
            if ($(panelSelector).is(":hidden")) {
                // jos piilossa ja hiiri saapuu ylle
                $(dropDownSelector).attr("src", unCheckedImage.replace(".png", "_hover.png"));
            } else {
                // jos näkyvissä ja hiiri saapuu ylle
                $(dropDownSelector).attr("src", unCheckedImage.replace(".png", "_on_hover.png"));
            }
        },
        function() {
            if ($(panelSelector).is(":hidden")) {
                // jos piilossa ja hiiri poistuu
                $(dropDownSelector).attr("src", unCheckedImage);
            } else {
                // jos näkyvissä ja hiiri poistuu
                $(dropDownSelector).attr("src", checkedImage);
            }
        }
    );
    $(dropDownSelector).click(function() {
        triggerDropDownPanel(dropDownSelector, panelSelector, imagePath);
    });
    
    $(document).click(function(event) {
        if ($(panelSelector).is(":visible")) {
            if ($(event.target).closest(".disable-auto-close").length == 0) {
                triggerDropDownPanel(dropDownSelector, panelSelector, imagePath);
            }
        }
    });
}

function triggerDropDownPanel(dropDownSelector, panelSelector, imagePath) {
    if ($(panelSelector).is(":hidden")) {
        // Hide others, slide in the extended content and change button state
        jQuery.each($(".dropdown-image"), function() {
            $(this).attr("src", $(this).attr("src").replace("_on", ""));
        });
        $(".extended-content:visible").slideUp("fast");
        $(dropDownSelector).attr("src", imagePath);
        $(panelSelector).slideDown();
    } else {
        $(panelSelector).slideUp();
        $(dropDownSelector).attr("src", $(dropDownSelector).attr("src").replace("_on", ""));
    }
    return false;
}

function createToggleButton(containerSelector, imagePath) {

    var unCheckedImage = imagePath;
    var unCheckedImageHover = imagePath.replace(".png", "_hover.png");
    var checkedImage = imagePath.replace(".png", "_on.png");
    var checkedImageHover = imagePath.replace(".png", "_on_hover.png");

    //preload images
    jQuery("<img>").attr("src", unCheckedImage);
    jQuery("<img>").attr("src", unCheckedImageHover);
    jQuery("<img>").attr("src", checkedImage);
    jQuery("<img>").attr("src", checkedImageHover);
    
    $(containerSelector + " input").hide();
    $(containerSelector + " label").hide();

    // get original AutoPostBack event handler
    var aspnetOnClick = $(containerSelector).find("input").attr("onclick");

    // set first image    
    if ($(containerSelector).find("input").attr("checked"))
      $(containerSelector).css("background-image", "url(" + checkedImage + ")");
    else
      $(containerSelector).css("background-image", "url(" + unCheckedImage + ")");

    $(containerSelector).hover(
      function() {
          if ($(this).find("input").attr("checked"))
              $(this).css("background-image", "url(" + checkedImageHover + ")");
          else
              $(this).css("background-image", "url(" + unCheckedImageHover + ")");
      },
      function() {
          if ($(this).find("input").attr("checked"))
              $(this).css("background-image", "url(" + checkedImage + ")");
          else
              $(this).css("background-image", "url(" + unCheckedImage + ")");
      }
    );

    $(containerSelector).click(function() {
      if ($(this).find("input").attr("checked")) {
          $(this).find("input").removeAttr("checked");
          $(this).css("background-image", "url(" + unCheckedImage + ")");
      }
      else {
          $(this).find("input").attr("checked", "checked");
          // Jos kyseessä on radio button, käydään läpi kaikki sisar-divit ja korvataan niiden taustakuvasta _on.png -> .png
          if ($(this).children("input[type=radio]").size() > 0) {
              $(this).siblings().each(function() {
                  $(this).find("input").removeAttr("checked");
                  $(this).css("background-image", $(this).css("background-image").replace("_on.png", ".png"));
              });
          }
          $(this).css("background-image", "url(" + checkedImage + ")");
      }
      // trigger AutoPostBack, if any
      if (aspnetOnClick !== null) {
          aspnetOnClick();
      }
    });
}

// function to show popup from flash cover flow
// state variable here because flash was ignoring it
var onTsemppisKaruselliItemSelected;

$(function() {
    onTsemppisKaruselliItemSelected = function(url) {
        var karuselliColorboxSettings = {
            href: url + "&timestamp=" + new Date().getTime(),
            open: true,
            width: 500,
            height: 500,
            close: "Sulje"
        };
        $.fn.colorbox(karuselliColorboxSettings);
    };
    $("#datepicker").datepicker({ showAnim: 'fadeIn', duration: 'fast', showOn: 'button', buttonImage: '/_layouts/Endero.Atria.Web/images/calendar.gif', buttonImageOnly: true });
    createFlashFacebox("a[rel='flashvideopopup'], input:button[rel='flashvideopopup']", 622, 350);
});


jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

/* We check if the recipe or the ingredients have too many lines or characters */
function checkReceiptAndIngredients() {
    var ingredients = $.countLines(".FieldIncredients"),
        instructions = $.countLines(".FieldInstructions"),
        totalIngredientsLines = ingredients.actual + ingredients.wrapped,
        totalInstructionLines = instructions.actual + instructions.wrapped + instructions.wraps;

    if (totalIngredientsLines > 20) {
        $("#textAreaError").html("Keittokirjan ainesosaluetteloon sopii n. 20 rivi&auml; teksti&auml;. Ole hyv&auml; ja jatka seuraavaan kappaleeseen tai tiivist&auml; teksti&auml;.");
        $("#textAreaError").show();
        return false;
    }
    if (totalInstructionLines > 30) {
        $("#textAreaError").html("Keittokirjan valmistusohjeisiin sopii n. 20 rivi&auml; teksti&auml;. Ole hyv&auml; ja jatka seuraavalle sivulle tai tiivist&auml; teksti&auml;.");
        $("#textAreaError").show();
        return false;
    }
    $("#textAreaError").hide();
}
$(function() {
    $(".CookbookField").bind("focus blur keyup", function() {
        return checkReceiptAndIngredients();
    });
});


/* Korjaa web parttien drag & drop bugin */
function MSOLayout_GetRealOffset(StartingObject, OffsetType, EndParent) { var realValue = 0; if (!EndParent) EndParent = document.body; for (var currentObject = StartingObject; currentObject && currentObject != EndParent && currentObject != document.body; currentObject = currentObject.offsetParent) { var offset = eval('currentObject.offset' + OffsetType); if (offset) realValue += offset; } return realValue; }

var autoPostBackTextBoxTimeoutID = 0;
function bindAutoPostBackTextBox(clientid, uniqueid) {
    $("#" + clientid).keyup(function(event) {
        if (autoPostBackTextBoxTimeoutID)
            window.clearTimeout(autoPostBackTextBoxTimeoutID);
        var timeout = 2000 / $(this).val().length;
        if (timeout < 500)
            timeout = 500;
        autoPostBackTextBoxTimeoutID = window.setTimeout("__doPostBack('" + uniqueid + "', '')", timeout);
    });
}

function createIframeFacebox(selector, width, height) {
    $(selector).click(function() {
        $.facebox("<iframe src='" + $(this).attr("href") + "' width='" + width + "' height='" + height + "' marginwidth='0' marginheight='0' />");
        return false;
    });
}
function createFlashFacebox(selector, width, height) {
    $(selector).click(function() {
        var flashDivId = "flashcontent_" + $(this).attr('id');
        var flashUrl = "";
        if ($(this).is("a"))
            flashUrl = $(this).attr('href');
        if ($(this).is("input:button"))
            flashUrl = $(this).attr('title');
        
        $.facebox("<div id='" + flashDivId + "'><center><img src='/videot/palvelut/video_noflash.jpg' alt='Sinulla ei ole flashplayeriä koneellasi' width='512' height='288' /></center></div>");
        var so_facebox = new SWFObject("/SiteCollectionDocuments/Flash/videoplayer622x350.swf", "so_facebox", width, height, "9.0.115", "#ffffff");
        so_facebox.addVariable("vidURL", flashUrl); // määritetään videon nimi ja sijainti
        so_facebox.addParam('menu', 'false');
        so_facebox.write(flashDivId);
        return false;
    });
}


