var Ajax;
if (Ajax && (Ajax != null)) {
	Ajax.Responders.register({
	  onCreate: function() {
        if($('spinner') && Ajax.activeRequestCount>0)
          Effect.Appear('spinner',{duration:0.5,queue:'end'});
	  },
	  onComplete: function() {
        if($('spinner') && Ajax.activeRequestCount==0)
          Effect.Fade('spinner',{duration:0.5,queue:'end'});
	  }
	});
}

/**
 * Boxy
 */
/*
var allDialogs = [];
var seq = 0;
*/
function create(url, el, options) {
    options = $.extend({title: ""}, options || {});
    //var dialog =
            new Boxy("<div style='text-align: center;'><a href='#' onclick='Boxy.get(this).hide(); return false'><img src=\""+url+"\" title=\"Kuva sulkeutuu klikkaamalla\" /><br /><br /><img src='../../images/layout/sulje.jpg' alt='' /></a></div>", options);
    //allDialogs.push(dialog);
    return false;
}
/*
function recent() { return allDialogs[allDialogs.length-1]; }
function tweenUp() { recent().tween(400,400); }
function tweenDown() { recent().tween(100,100); }
function getTitle() { alert(recent().getTitle()); }
function setTitle() { recent().setTitle(prompt("Enter new title:")); }
*/


$(document).ready(function() {
    $('img').error(function(){
//        $(this).attr('alt', 'missing');
    });


    /**
     * Configuration

jCarousel accepts a list of options to control the appearance and behaviour of the carousel. Here is the list of options you may set:

Property 	Type 	Default 	Description
     
vertical 	bool 	false 	Specifies wether the carousel appears in horizontal or vertical orientation. Changes the carousel from a left/right style to a up/down style carousel.
start 	integer 	1 	The index of the item to start with.
offset 	integer 	1 	The index of the first available item at initialisation.
size 	integer 	Number of existing <li> elements if size is not passed explicitly 	The number of total items.
scroll 	integer 	3 	The number of items to scroll by.
visible 	integer 	null 	If passed, the width/height of the items will be calculated and set depending on the width/height of the clipping, so that exactly that number of items will be visible.
animation 	mixed 	"fast" 	The speed of the scroll animation as string in jQuery terms ("slow" or "fast") or milliseconds as integer (See jQuery Documentation). If set to 0, animation is turned off.
easing 	string 	null 	The name of the easing effect that you want to use (See jQuery Documentation).
auto 	integer 	0 	Specifies how many seconds to periodically autoscroll the content. If set to 0 (default) then autoscrolling is turned off.
wrap 	string 	null 	Specifies whether to wrap at the first/last item (or both) and jump back to the start/end. Options are "first", "last" or "both" as string. If set to null, wrapping is turned off (default). You can also pass "circular" as option to enable support for circular carousels. See the example Circular carousel on how to implement it.
initCallback 	function 	null 	JavaScript function that is called right after initialisation of the carousel. Two parameters are passed: The instance of the requesting carousel and the state of the carousel initialisation (init, reset or reload)
itemLoadCallback 	function 	null 	JavaScript function that is called when the carousel requests a set of items to be loaded. Two parameters are passed: The instance of the requesting carousel and the state of the carousel action (prev, next or init). Alternatively, you can pass a hash of one or two functions which are triggered before and/or after animation:

itemLoadCallback: {
  onBeforeAnimation: callback1,
  onAfterAnimation: callback2
}

itemFirstInCallback 	function 	null 	JavaScript function that is called (after the scroll animation) when an item becomes the first one in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li> object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init). Alternatively, you can pass a hash of one or two functions which are triggered before and/or after animation:

itemFirstInCallback: {
  onBeforeAnimation: callback1,
  onAfterAnimation: callback2
}

itemFirstOutCallback 	function 	null 	JavaScript function that is called (after the scroll animation) when an item isn't longer the first one in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li> object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init). Alternatively, you can pass a hash of one or two functions which are triggered before and/or after animation:

itemFirstOutCallback: {
  onBeforeAnimation: callback1,
  onAfterAnimation: callback2
}

itemLastInCallback 	function 	null 	JavaScript function that is called (after the scroll animation) when an item becomes the last one in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li> object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init). Alternatively, you can pass a hash of one or two functions which are triggered before and/or after animation:

itemLastInCallback: {
  onBeforeAnimation: callback1,
  onAfterAnimation: callback2
}

itemLastOutCallback 	function 	null 	JavaScript function that is called when an item isn't longer the last one in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li> object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init). Alternatively, you can pass a hash of one or two functions which are triggered before and/or after animation:

itemLastOutCallback: {
  onBeforeAnimation: callback1,
  onAfterAnimation: callback2
}

itemVisibleInCallback 	function 	null 	JavaScript function that is called (after the scroll animation) when an item is in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li> object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init). Alternatively, you can pass a hash of one or two functions which are triggered before and/or after animation:

itemVisibleInCallback: {
  onBeforeAnimation: callback1,
  onAfterAnimation: callback2
}

itemVisibleOutCallback 	function 	null 	JavaScript function that is called (after the scroll animation) when an item isn't longer in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li> object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init). Alternatively, you can pass a hash of one or two functions which are triggered before and/or after animation:

itemVisibleOutCallback: {
  onBeforeAnimation: callback1,
  onAfterAnimation: callback2
}

buttonNextCallback 	function 	null 	JavaScript function that is called when the state of the 'next' control is changing. The responsibility of this method is to enable or disable the 'next' control. Three parameters are passed: The instance of the requesting carousel, the control element and a flag indicating whether the button should be enabled or disabled.
buttonPrevCallback 	function 	null 	JavaScript function that is called when the state of the 'previous' control is changing. The responsibility of this method is to enable or disable the 'previous' control. Three parameters are passed: The instance of the requesting carousel, the control element and a flag indicating whether the button should be enabled or disabled.
buttonNextHTML 	string 	<div></div> 	The HTML markup for the auto-generated next button. If set to null, no next-button is created.
buttonPrevHTML 	string 	<div></div> 	The HTML markup for the auto-generated prev button. If set to null, no prev-button is created.
buttonNextEvent 	string 	"click" 	Specifies the event which triggers the next scroll.
buttonPrevEvent 	string 	"click" 	Specifies the event which triggers the prev scroll.

     */
    var conf={
        visible: 3,
        scroll: 3
    };

   $('.jcarousel-skin-tango:visible').jcarousel(conf);
    //$('#recommendedBooks').jcarousel(conf);
    //$('#comingBooks').jcarousel(conf);
   //$('#raisedcarousel').jcarousel(conf);

});

function selectTab(tabId) {
//    el.onClick = 'return false;';
//    $('#ajaxtabs .selected').onClick = '';
    $('#ajaxtabs .selected').removeClass('selected');
    $('#'+tabId).addClass('selected');    
}

function makeSortable(id, isBranch) {
    if(isBranch){
        $('#' + id).siblings('.saveLink').show();
        $('#' + id).siblings('.editLink').hide();
        $('#' + id).Sortable(
            {
                accept : 		'branchItem',
                helperclass : 	'sorthelper',
                activeclass : 	'sortableactive',
                hoverclass : 	'sortablehover',
                opacity: 		0.8,
                fx:				200,
                axis:			'vertically',
                opacity:		0.4,
                revert:			true
            }
        );
    } else {
        $('#' + id + ' .saveLink').show();
        $('#' + id + ' .editLink').hide();
        $('#' + id + ' .leafList').Sortable(
            {
                accept : 		'leafItem',
                helperclass : 	'sorthelper',
                activeclass : 	'sortableactive',
                hoverclass : 	'sortablehover',
                opacity: 		0.8,
                fx:				200,
                axis:			'vertically',
                opacity:		0.4,
                revert:			true
            }
        );
    }
}

function saveSortable(id, url, isBranch) {
    if(isBranch){
        $('#' + id).siblings('.saveLink').hide();
        $('#' + id).siblings('.editLink').show();
        $('#' + id).SortableDestroy();
        var order = 1;
        var newOrder = "";
        $('#' + id + ' .branchItem').each(
                function(i){
                    scPath = $(this).attr("id").split("sc_")[1];
                    if(scPath){
                        newOrder += (order > 1 ? "," : "") + scPath + ":" + order;
                        order++;
                    }
                });
        if(confirm("Tallennetaanko uusi järjestys: " + newOrder))
            $.post(url, {id: id.split("_")[1], newOrder: newOrder});
    } else {
        $('#' + id + ' .saveLink').hide();
        $('#' + id + ' .editLink').show();
        $('#' + id + ' .leafList').SortableDestroy();
        var order = 1;
        var newOrder = "";
        $('#' + id + ' .leafItem').each(
                function(i){
                    scPath = $(this).attr("id").split("sc_")[1];
                    if(scPath){
                        newOrder += (order > 1 ? "," : "") + scPath + ":" + order;
                        order++;
                    }
                });
        if(confirm("Tallennetaanko uusi järjestys: " + newOrder))
            $.post(url, {id: id.split("_")[1], newOrder: newOrder});
    }
}

function addNewSubCategory(adder, ordering, url, parentId) {
    $(adder).before('<li>' +
                    '<input style="border: 0px;border-bottom:1px dashed; margin-right:5px" name="title" type="text" size="12" value="" />' +
                    '<input type="button" value="&gt;" onClick="saveNewSubCategory(this.previousSibling, '+ordering+', \''+url+'\', '+parentId+')"/>' +
                    '</li>')
}

function saveNewSubCategory(inputEl, ordering, url, parentId) {
    $.post(url, {newSubCategory:true, title:$(inputEl).val(), ordering:ordering, parentId: parentId})
}

/**
 * Uuden pääkategorian lisääminen
 * @param adder
 * @param ordering
 * @param url
 * @param parentId
 */
function addNewCategory(adder, ordering, url, parentId) {
    $(adder).before('<li>' +
                    '<input style="border: 0px;border-bottom:1px dashed; margin-right:5px" name="title" type="text" size="12" value="" />' +
                    '<input type="button" value="&gt;" onClick="saveNewCategory(this.previousSibling, '+ordering+', \''+url+'\')"/>' +
                    '</li>')
}

/**
 * Pääkategorian tallentaminen
 * @param inputEl
 * @param ordering
 * @param url
 */
function saveNewCategory(inputEl, ordering, url) {
    $.post(url, {newSubCategory:true, title:$(inputEl).val(), ordering:ordering})
}

function showMessage(id, html) {
    $('#htmlmessage_'+id).html(html);
    var messageElem=$('#message_'+id);
    messageElem.fadeIn(500, function() {
    	messageElem.delay(2000).fadeOut(500);
    });
    return true;
}


/**
 * Lähetä -linkki formin toiminnallisuus.
 */
function showSendLinkForm() {
	$('#sendlinkurl_field').get(0).value=document.location.href;
	$('#sendlinktitle_field').get(0).value=document.title;
	hide_and_show(['content-inner div'], ['content-form']);
}

function hideSendLinkForm() {
	show_and_hide(['content-inner div'], ['content-form']);
    $('div.tabcontent').removeAttr('style');
}

