function CategorySelector(selector) {
	var me = this;
	var currentCategorySelected = null;
	var currentPageSelected = 1;
	var maxNumPages = 3;
	
    var _currentCategory = null;    
    var _currentCategoryId = null;
    var _selectedPage = null;
    
    me.onStateChanged = function () {
        
    };
    
	me.init = function() {
		_bindEvents();
	};	
	
    me.setCurrentPage = function(index) {
		_setCurrentPage(index);
		_raiseOnStateChanged();
    };    
    

    function _setCurrentPage(index) {
        if (_selectedPage) {
            $(selector)
                .find('.Paginator a[href=#'+(_selectedPage)+']')
                .removeClass('selected');                
        }
        _selectedPage = index;      
        $(selector)
            .find('.Paginator a[href=#' + index+']')
            .addClass('selected');
    }
    function _changePage(cmd) {
        switch(cmd) {
            case 'before' : cmd = (_selectedPage && (_selectedPage > 1))? (_selectedPage * 1) - 1 : 3 ;
                break;
            case 'next' : cmd = (_selectedPage && (_selectedPage < 3))? (_selectedPage * 1) + 1 : 1 ;     
                break;			
        }
        _setCurrentPage(cmd);
        _raiseOnStateChanged();
    }
    
    function _raiseOnStateChanged() {       
        me.onStateChanged(_selectedPage || 1,_currentCategoryId || -1);
    }
    
	function _bindEvents() {                
        var lastSelectedElement 
        var classToUse = null;
		$(selector)            
            .find('.Paginator a')
            .click(function () {
                var cmd = $(this).attr('href').replace('#',"");
                _changePage(cmd);               
                return false;
            });
	};
	
}

function NewsDashboard( options) {
	var opts = {		
		dashboardSelector : '.DashBoard',
		categorySelector : '.Categories',
        handlerUrl : null
	};
	
	$.extend(opts, options);		
	var catsSelector = new CategorySelector(opts.categorySelector);
    
    catsSelector.onStateChanged = function (page,IdCategory) {
        //console.log("page, IdCategory " + page + ', ' + IdCategory);
        page = page - 1;
        if ((page < 0) || (page > 2)) {
            page = 0;
        }
        _loadNewsInCategory(IdCategory, page);
    };
	
	var dashboard = $(opts.dashboardSelector);
	
	var me = this;
	me.init = function () {	
		catsSelector.init();
		catsSelector.setCurrentPage(1);		
	}
	function _loadNewsInCategory(category, page) {
        dashboard
            .empty()
            .append($('<div class="AjaxLoader">&nbsp;</div>'))
    		.load(opts.handlerUrl, { nocache: (new Date()).getUTCDate(), pageNumber : page, IdCategory : 5 }, function () { 				
                showImagesWhenPossible(dashboard);
				dashboard
					.find('ul')
					.fadeIn('fast')
					.end()
					.find('.AjaxLoader')
					.remove();
				
            });
	}
	
	function showImagesWhenPossible(ds) {
		ds.find('li.noticia').each(function () {
			var ele = $(this);
			var ima = ele.find('.ima img');
			if (ima.length > 0) {	//there is at least one image
				ele.find('.Nota p').remove();
				ele.find('.Nota').append(ima);
				ele.addClass('ImageHolder');
				var w = ima.width();
				var h = ima.height();
				if (w > 200) {
					var prop = 200 / w;
					ima.width(200);
					ima.height(h * prop);
				}
			}
		});
	}		
}

function Paginator(selector, numPages) {
	var tpl = '<div class="Paginator Right"><ul>' +
					'<li><a class="back" href="#before" cmd="#before" ><span>&lt;&lt;</span></a></li>' +
					 '{PAGES}' +
					'<li><a class="forward" href="#next" cmd="#next"><span>&gt;&gt;</span></a></li></ul><div class="DoClear"></div></div>';
	
	var aPageTpl = '<li><a href="#{NUMBER}" cmd="#{NUMBER}"><span>{NUMBER}</span></a></li>';
	
	var me = this;
	var _selectedPage = null;
	
	me.onPageChanged = function () {};
	
	me.changePage = function (cmd) {
		_changePage(cmd);
	}
	
	function _renderItems(numPages) {
		var output = '';
		for (var ix = 0; ix < numPages; ix++) {
			output += aPageTpl.replace(/{NUMBER}/gi,ix+1);
		}
		return output;
	}	
	
	function _setCurrentPage(index) {
        if (_selectedPage) {
            $(selector)
                .find('.Paginator a[cmd=#'+(_selectedPage)+']')
                .removeClass('selected');                
        }
        _selectedPage = index;      
        $(selector)
            .find('.Paginator a[cmd=#' + index+']')
            .addClass('selected');
    }
    function _changePage(cmd) {
		
        switch(cmd) {
            case 'before' : cmd = (_selectedPage && (_selectedPage > 1))? (_selectedPage * 1) - 1 : numPages;
                break;
            case 'next' : cmd = (_selectedPage && (_selectedPage < numPages ))? (_selectedPage * 1) + 1 : 1 ;     
                break;		
        }
		
        _setCurrentPage(cmd);
        _raiseOnStateChanged();
    }
    
    function _raiseOnStateChanged() {       
        me.onPageChanged(_selectedPage);
    }
	
	function _bindEvents() {
		$(selector)
			.find('.Paginator a')
			.click(function () {
				var cmd = $(this).attr('cmd').replace('#','');				
				//console.log('cmd antes ' + cmd);
                _changePage(cmd);               
                return false;
			});
	}
	
	me.init = function () {
		renderedItems = _renderItems(numPages);		
		var output = tpl.replace('{PAGES}',renderedItems);
		
		$(selector).append($(output));
		
		_bindEvents();		
	}
}

function BlogLister(options) {
	var opts = {		
		blogSelector : '.BlogDataSection',		
		paginatorSelector : '.BlogPaginator',
        handlerUrl : null,
		numPages : 2
	}; 
	
	$.extend(opts, options);	
	
	var paginator = new Paginator(opts.paginatorSelector, opts.numPages);
	var blogObject = $(opts.blogSelector);
	var me = this;
	
	me.init = function () {
		paginator.init();		
		paginator.onPageChanged = function (page) {
			_loadNewBlogPage(page);
		}		
		paginator.changePage(1);
	}
	
	function _loadNewBlogPage(page) {
		blogObject
			.empty()
			.append('<div class="AjaxLoader">&nbsp;</div>')
			.load(opts.handlerUrl, { nocache : (new Date()).getUTCDate(), pageNumber : page, action : 'getBlogs' }, function()  {				
				blogObject															
					.find('.AjaxLoader')
					.remove();
			});
		
	}
}

function HighlightedPost(options) {
	var opts = {
		dataSelector : null,
		renderInDiv : '.Destacados-Wrapper'
	}
	
	$.extend(opts, options);
	
	var template = $("<div class='DestacadosGallery'><div class='img-big-container'></div><div class='NoteSelector'><ul><li class='NoteDescription'></li><li class='Thumbs'><ul class='ThumbHolder'></ul></li></ul><div class='DoClear'></div></div></div>");
	$(opts.renderInDiv).prepend(template);
	//template.find('.NoteSelector').css('opacity',0.5);
	var data = $(opts.dataSelector).find('.noticia');
	
	data.each(function () {
		var currentEle = $(this);		
		var thumb = currentEle.find('.ImageThumb img')		
		var aTitle = currentEle.find('H2.Title a');
		//aTitle.attr('title',aTitle.text()).text($.ellipsis(aTitle.text(), { max : 55}));
		
		thumb.data('PostTitle', currentEle.find('H2.Title'));
		thumb.data('CommentLink', currentEle.find('p.CommentUrl'));
		thumb.data('ImageBig', currentEle.find('.ImageBig img'));		
		template.find('.ThumbHolder').append($('<li></li>').append(thumb));		
		
		thumb.click(function() {
			window.location.href = $(this).data('PostTitle').find('a').attr('href');
		});
		var w = thumb.width();
		var h = thumb.height();
		if (w > 92) {
			var prop = 92 / w;
			thumb.width(92);
			thumb.height(h * prop);
		}
	});	
	var hov = null;
	template.find('.ThumbHolder li img').hover(function () { 			
			var ele = $(this);			
			//clearTimeout(hov);
			//var hov = setTimeout(function () {
				//clearTimeout(hov);
				var img = ele.data('ImageBig');
				template.find('.img-big-container').find('img').css('display','none');
				template.find('.img-big-container').append(img.css('display','none'));			
				template.find('.NoteDescription').children().remove().end().append(ele.data('PostTitle')).append(ele.data('CommentLink'));									
				img.fadeIn('slow');
			//}, 300);
			
		}, function () {});
		
	setTimeout(function() { template.find('.ThumbHolder li img:first').hover(); },500);
 	//if (!$.browser.mozilla) setTimeout(function() { template.cornerz({radius:5, borderWidth: 1}); } ,1000);
}
// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing.easeIn = function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	};

function home_jobs(url_to_data) {
	
	try {   	         			
		//show the big thumbnails when the user rolls over the video links
        $('.VideoGallery .tubepress_container .tubepress_thumb a')
			.hover(function () {
                var current = $(this);
                //find the clone
				var img = current.parent().find('img.tempClone'); 
				//changes the text of the title and preview components
                tubepress_preview_video_info(current.attr('p_title'), current.attr('p_gallery_id'), current.attr('p_description'));
				//if no clone image, create one and add it to the parent element
                img = img.length? img : current.find('img').clone().addClass('tempClone').css('display','none').appendTo(current.parent());
				//show the big thumbnail
                img.fadeIn();
            },function () {
				//fade out the big thumbnail on roll out
				var current = $(this);
                current.parent().find('img.tempClone').fadeOut();
            });
			
		$('.tubepress_container .tubepress_thumb a')
            .click(function () { //when a thumbnail is clicked change the embed info, the title and the description
				var current = $(this);
                tubePress_normalPlayer(current.attr('p_embed'), current.attr('p_w'), current.attr('p_title'), current.attr('p_gallery_id'), current.attr('p_description'));
                return false;
            });  

		$('.tubepress_description').text($.ellipsis($('.tubepress_description').text(), {max: 100}));
		
        $('.VideoGallery .tubepress_video_thumbs').hover(function () {}, function() {
			var current = $(this);
			tubepress_restore_selected_video(current.attr('p_gallery_id'));
         });    
		 
		
		var items = $('.gallery-item');
		$('.GalleryContainer .Slider').append(items);
		$('h2.GalleryTitle').appendTo('.GalleryContainer .G-Title');
	
	
		 
		var w = $('.GalleryContainer .Slider .gallery-item').length * 180;		
		$('.GalleryContainer .Slider').css({ 'position':'absolute'}).css('left',0).width(w);						
		var limite = w - 908;
		
		$('a.ArrowRight').click(function () { 			
			var x = parseInt(($('.GalleryContainer .Slider').css('left')+ '').replace('px'),10);		
			if (x > -limite)
				$('.GalleryContainer .Slider').animate({left: '-=180' }, { "duration": "slow", "easing": "easeInCubic" });  return false; 
		});
		$('a.ArrowLeft').click(function () { 			
			var x = parseInt(($('.GalleryContainer .Slider').css('left')+ '').replace('px'),10);
			if (x < 0)
				$('.GalleryContainer .Slider').animate({left: '+=180' }, { "duration": "slow", "easing": "easeInCubic" });  return false; 
		});
		

		var destacadosPlayer = new HighlightedPost({ dataSelector : '.Destacados-Wrapper .data' });
		
		//Create the News-Dashboard
        var ds = new NewsDashboard( { handlerUrl :  url_to_data });
        ds.init();
		var bl = new BlogLister( { handlerUrl : url_to_data } );
		bl.init();
    } 
    catch (e) {
		
	}
}


function load_novedad(id, url_to_data) {
	$('#post-holder')
		.empty()
		.append('<div class="AjaxLoader">&nbsp;</div>')
		.load(url_to_data, 
			{ nocache : (new Date()).getUTCDate(), 
			  post_id : id, 
			  action : 'getPost' },
			 function (data) {
				$('#post-holder').find('.AjaxLoader').remove();
			 });
}

function init_novedades(url_to_data) {
	
	$('#Suplementos').val(-1);
	$('#Medios').val(-1);
	
	
	$('#Medios').bind('change', function () {
		$('#Suplementos').val(-1);
		var id = $(this).val();
		if (id != -1) 
			load_novedad(id, url_to_data);
	});
	
	$('#Suplementos').bind('change', function () {
		$('#Medios').val(-1);
		var id = $(this).val();
		if (id != -1) 
			load_novedad(id, url_to_data);
	});
	
	var id =$('#Medios').find('option:last').attr('value');
	if (id != -1) 
		load_novedad(id, url_to_data);
}

function page_jobs(url_to_data) {        
	
	$('.navigation .alignleft, .navigation .alignright').each(
		function () {
			if ($(this).children().length == 0 ) {
				$(this).hide();
			}
		}
	);
	//copy sociable plugin to top 	
	//$('div.sociable').clone().prependTo('.post');	
	
	//add the title of the image in the prev and next links
	$('.ImageLink').each(function () {
		var link = $(this).find('a');
		var tit = link.attr('title');
		if (tit) {
			var link2 = link.clone();
			link2.text(tit);
			var p = $('<p></p>').append(link2);
			$(this).append(p);
		}
	});
	
	$('.gallery-item').each(function () {
		
	});
	
	if ($('#post-holder').length > 0) {
		init_novedades(url_to_data);
	}
	
	//add the Increase / Decrease / Print Behavior. Remember this is defined in the sociable tagLine
    $('.increase')        
        .click(function() {
            $('.post h2, .entry p, p.Excerpt').increaseFontSize(.2);
        });
    
    $('.decrease')        
        .click(function() {
            $('.post h2, .entry p, p.Excerpt').decreaseFontSize(.2);
        });
    $('a.print-cmd')
        .click(function () {
            window.print();
        });
}


$.fn.increaseFontSize = function (percentage) {
  percentage = percentage || 0.1;
  percentage = 1 + percentage;
  return this.each(function (i, ele) {
      var currentSize = parseFloat($(this).css('fontSize'),10);
      currentSize *= percentage;
      $(this).animate({fontSize : currentSize});
  });
};

$.fn.decreaseFontSize = function (percentage) {
  percentage = percentage || 0.1;
  percentage = 1 - percentage;
  return this.each(function (i, ele) {
      var currentSize = parseFloat($(this).css('fontSize'),10);
      currentSize *= percentage;
      $(this).animate({fontSize : currentSize});
  });
};

$.fn.initialValue = function(txt) {
    return this.each(function(i, ele){
        if ($.trim($(this).val()) == '') {
            $(this)
				.val(txt)
				.addClass('dummyText');
        }
        $(this)
            .bind('focus', function () { if ($(this).val() == txt ) $(this).val("").removeClass('dummyText'); })
            .blur(function () { if ($.trim($(this).val()) == '') $(this).val(txt).addClass('dummyText'); });
            
    });
}


$(function () {	
	$('.FlashContent').each(function (i, val) {
		var ele = $(this);
		var source = ele.attr('flash_source');
		var nc = (source.indexOf('?') > -1)? '&nc=' : '?nc=';
		source += (nc + (new Date()).getUTCDate());					
		ele.flash({ src: source,
				width: ele.attr('flash_width'),
				height: ele.attr('flash_height'),
				scale: "noscale",
				wmode: "transparent"			
			},
			{ expressInstall: false  });
	});
	//to support transparent backgrounds in the header
	$('<div class="bg"></div>')
		.prependTo('.menu ul')		
		.css('opacity',0.5);
	$('.FormText').each(function () {
		
		var initValue = $(this).attr('initial_value');
		if (initValue) {
			$(this).initialValue(initValue);
		}
	});
});

jQuery.extend(
    {
        ellipsis: function(str, opts) {
            var options =
                {
                    ellipsisText: "...",
                    max: 150,
                    truncateWords: true
                };

            $.extend(options, opts);

            //TODO: check that options.max > options.ellipsisText
            if (((typeof (str) != 'undefined') && str.length <= options.max) || (options.max - options.ellipsisText.length < 0)) {
                return str;
            }
			
			if (typeof (str) != 'undefined') {
				str = str.substring(0, options.max - options.ellipsisText.length) + options.ellipsisText;
			}
            return str;
        }
	});
