
// page init
jQuery(function(){
	clearInputs();
	initGallery();
});

// clear inputs
function clearInputs(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
};

// gallery init
function initGallery(){
	jQuery('div.slidebox').scrollGallery({
		pauseOnHover:true,
		autoRotation:false,
		switchTime:5000, // [1000 - 1sec]
		duration:650 // [1000 - 1sec]
	});

};

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div.frame',
		slider:'>ul.slideshow',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.prev',
		btnNext:'a.next',
		activeClass:'active',
		disabledClass:'disabled',
		generatePagination:'div.pg-holder',
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		pauseOnHover:true,
		autoRotation:false,
		stopAfterClick:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		afterInit:false,
		vertical:false,
		step:false
	},_options);

    // Initialize Menu

    if (  jQuery(_options.btnPrev ).size() > 0 && jQuery(_options.btnNext ).size() ){
        if ( $("#nav li a.active").size() == 0 ){
            var ilink = $("#nav li:eq(0) a");
            ilink.addClass("active");
            $("span#slogan_section").html( ilink.html() );
        }
        
    }

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _this);
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev);
		var _btnNext = jQuery(_options.btnNext);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _curNum = jQuery(_options.curNum, _this);
		var _allNum = jQuery(_options.allNum, _this);
		var _pauseButton = jQuery(_options.pauseButton, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _pauseClass = _options.pauseClass;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;
		var _circleSlide = _options.circleSlide;
		var _stopAfterClick = _options.stopAfterClick;
		var _afterInit = _options.afterInit;

        // gallery init
		if(!_slides.length) return;
		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

        var _subSlider = jQuery(".rr_frame");
        var _menuButtons = jQuery("#nav li a");

		_slides.each(function(){
			_sumWidth+=jQuery(this).outerWidth(true);
			_sumHeight+=jQuery(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
					if(_offset < _sliderHolder.width()-_sumWidth) _offset = _sliderHolder.width()-_sumWidth;
				} else {
					_stepWidth = _sliderHolder.width();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				nextSlide();
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = jQuery('<ul />');
			for(var i=0; i<_stepCount; i++) jQuery('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			_pagerLinks = _list.children();
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						if(_stopAfterClick) stopAutoSlide();
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else if(_circleSlide) _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else if(_circleSlide) _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
			if(!_circleSlide) {
				_btnPrev.removeClass(_disabledClass);
				_btnNext.removeClass(_disabledClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
		}
		function switchSlide() {
			recalcOffsets();
            highlightMenu();
            if(_vertical){
                _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
                _subSlider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
            }
			else {
                _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
                _subSlider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
            }

			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_autoRotation = false;
		}
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}


        function highlightMenu(){
            if ( _btnPrev.size() > 0 && _btnNext.size() > 0 ){
                _menuButtons.each( function (){
                    $(this).removeClass("active");
                })
                var link = $("#nav").find("li:eq("+ ( _currentStep ) + ") a");
                link.addClass("active");
                $("span#slogan_section").html( link.html() );
            }
        }
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		recalcOffsets();
		refreshStatus();
		autoSlide();

        if ( $("li.active", $("#nav")).index() >= 0 ){
            _currentStep = $("li.active", $("#nav")).index();
            switchSlide();
        }

		// pause buttton
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}

		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
};

// clear inputs plugin
function clearFormFields(o){
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filterClass) o.filterClass = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass) == -1) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass) == -1) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
};

// star rating init
function initRating() {
	var rates = document.getElementsByTagName('ul');
	for (var i = 0; i < rates.length; i ++) {
		if (rates[i].className.indexOf('star-rating') != -1) {
			new StarRating({
				element:rates[i],
				onselect:function(num) {
					// rating setted event
				}
			})
		}
	}
}

// simple star raring module
function StarRating() {
	this.options = {
		activeClass:'active',
		settedClass:'setted',
		element:null,
		items:null,
		onselect:null
	}
	this.init.apply(this,arguments);
}
StarRating.prototype = {
	init: function(opt){
		this.setOptions(opt);
		if(this.element) {
			this.getElements();
			this.addEvents();
		}
	},
	setOptions: function(opt) {
		for(var p in opt) {
			if(opt.hasOwnProperty(p)) {
				this.options[p] = opt[p];
			}
		}
		if(this.options.element) {
			this.element = this.options.element;
		}
	},
	getElements: function() {
		// get switch objects
		if(this.options.items == null) {
			this.items = this.element.children;
		} else {
			if(typeof this.options.items === 'string') {
				this.items = this.element.getElementsByTagName(this.options.items);
			} else if(typeof this.options.items === 'object') {
				this.items = this.options.items;
			}
		}

		// find default active index
		for(var i = 0; i < this.items.length; i++) {
			if(this.hasClass(this.items[i],this.options.activeClass)) {
				this.activeIndex = i;
			}
			if(this.hasClass(this.items[i],this.options.settedClass)) {
				this.settedIndex = i;
			}
		}
	},
	addEvents: function() {
		for(var i = 0; i < this.items.length; i++) {
			this.items[i].onmouseover = this.bind(this.overHandler,this, i);
			this.items[i].onmouseout = this.bind(this.outHandler,this, i);
			this.items[i].onclick = this.bind(this.clickHandler,this, i);
		}
	},
	overHandler: function(ind) {
		this.hovering = true;
		this.hoverIndex = ind;
		this.refreshClasses();
	},
	outHandler: function(ind) {
		this.hovering = false;
		this.refreshClasses();
	},
	clickHandler: function(ind) {
		this.hovering = false;
		this.settedIndex = ind;
		if(typeof this.options.onselect === 'function') {
			this.options.onselect(ind);
		}
		this.refreshClasses();
		return false;
	},
	refreshClasses: function() {
		for(var i = 0; i < this.items.length; i++) {
			this.removeClass(this.items[i],this.options.activeClass);
			this.removeClass(this.items[i],this.options.settedClass);
		}
		if(this.hovering) {
			this.addClass(this.items[this.hoverIndex],this.options.activeClass);
		} else {
			if(typeof this.settedIndex === 'number') {
				this.addClass(this.items[this.settedIndex],this.options.settedClass);
			} else {
				if(typeof this.activeIndex === 'number') {
					this.addClass(this.items[this.activeIndex],this.options.activeClass);
				}
			}
		}
	},
	hasClass: function(el,cls) {
		return el && el.className ? el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')) : false;
	},
	addClass: function(el,cls) {
		if (el && !this.hasClass(el,cls)) el.className += " "+cls;
	},
	removeClass: function(el,cls) {
		if (el && this.hasClass(el,cls)) {el.className=el.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ');}
	},
	bind: function(f, scope, args){
		return function() {return f.apply(scope, [args] || arguments)}
	}
}

function loadAjaxRecommendationChanger(){
    $(".week-changer").live( "click",  function(e){
           var url = $(this).attr("ref");
           var navigation = $(this).attr("rel");
        
           var box = $("#recommendation_"+navigation);
           var height = box.height();
           box.parent(".rr_frame").css({ height: "460px" });

           box.before( '<div class="loader" style="visibility: none;"> <img src="/images/ajax-loader.gif" alt=""></div>');
           $(".loader").fadeIn("fast");

           box.fadeOut('slow');

           $.ajax({
              url: url,
              context: document.body,
              success: function( data ){
                box.replaceWith( data );
                box.parent(".rr_frame").css({ height: "" });
                  $(".loader").fadeOut("fast").remove();
                box.effect("highlight");
              }
           })
           return false;
       });
}


(function( $ ){

    $.fn.trailerMovie = function (options){

        var _options = jQuery.extend({}, options);

        //$("#movieTrailer").css({ "margin": "5px auto", "position": "absolute", "top": "-1000px" }).peKenburnsSlider();
        
        /*
        return this.each(function(){
            $(this).unbind("click").click(function(){
                //$("#movieTrailer").hide().css({ "position": "relative", "top": "0px" }).slideDown();
                return false;
            })

        });
        */
    }


})(jQuery);


window.WeekDayName = function ( day ) {
    var weekday=["Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado"];
    return weekday[ day ];
}

window.spanishDate = function (d){
	var monthname=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
	return " "+d.getDate()+" de "+monthname[d.getMonth()]+" de "+d.getFullYear()
}

$(document).ready(function(){


	if ( $("#movie-rating").size() > 0 ){
		var omodel = $("#movie-rating").attr("rel");
		var model_id = $("#movie-rating").attr("ref");

		$("#movie-rating").raty({
			path: '/images/raty/',
			click: function( score, evt ) {
				$.ajax({
				   url: "/valuation/" + omodel,
				   type: "POST",
				   data: { id: model_id , value: score },
				   success: function ( data ){
						$.fn.raty.start( data , '#movie-rating');
						// $("#value-score").html( data +" / 5 ")
				   }
				 });

			}
		});
		$.ajax({
           url: "/valuation/"+omodel+"/result",
           type: "POST",
           data: { id: model_id  },
           success: function ( data ){
                $.fn.raty.start( data , '#movie-rating');
                //$("#value-score").html( data +" / 5 ")
           }
         });
	}

    loadAjaxRecommendationChanger();
    if ( $("form.subscribe-form").size() > 0 ){
        $("form.subscribe-form").alertMovies();
    }

    //$("a.trailerMovie").trailerMovie({});
    $("a[rel^='prettyPhoto']").prettyPhoto({
        default_width: 460,
		default_height: 344,
        social_tools: '',
        allow_resize: false
    });

    $("a[rel^='close_prettyPhoto']").live("click",  function(){
       $.prettyPhoto.close();
    });


    $("a[rel^='prettyPhotoLogin']").prettyPhoto({
        show_title: false,
        theme: 'light_square',
        afterShowContent: function(){
            try{
                FB.XFBML.parse(document.getElementById('facebook_connect_button'));
            }catch( err ){

            }
        },
        markup: '<div class="pp_pic_holder"> \
                                <div class="ppt">&nbsp;</div> \
                                <div class="pp_top"> \
                                    <div class="pp_left"></div> \
                                    <div class="pp_middle"></div> \
                                    <div class="pp_right"></div> \
                                </div> \
                                <div class="pp_content_container"> \
                                    <div class="pp_left"> \
                                    <div class="pp_right"> \
                                        <div class="pp_content"> \
                                            <div class="pp_loaderIcon"></div> \
                                            <div class="pp_fade"> \
                                                <a href="#" class="pp_expand" title="Expand the image">Expand</a> \
                                                <div class="pp_hoverContainer"> \
                                                    <a class="pp_next" href="#">next</a> \
                                                    <a class="pp_previous" href="#">previous</a> \
                                                </div> \
                                                <div id="pp_full_res"></div> \
                                                <div class="pp_details"> \
                                                </div> \
                                            </div> \
                                        </div> \
                                    </div> \
                                    </div> \
                                </div> \
                                <div class="pp_bottom"> \
                                    <div class="pp_left"></div> \
                                    <div class="pp_middle"></div> \
                                    <div class="pp_right"></div> \
                                </div> \
                            </div> \
                            <div class="pp_overlay"></div>'

    });

    var d = new Date();
    window.spanishDate(d)
    $(".intro .block p").html("hoy "+window.WeekDayName(d.getDay())+" <span> "+ window.spanishDate(d)  +" </span> recomendamos" );
});


/**
 * Plugin for alert Movies Footer
 *
 */
(function( $ ){

    $.fn.alertMovies = function (){
        var form = $(this);
        var name = form.find("input#name");
        var email = form.find("input#email");
        var original_name = name.val();
        var original_email = email.val();

        hideMessages( );

        $(this).find("input.btn-submit").unbind("click").live("click", function(){
            var new_name = form.find("input#name").val();
            var new_email = form.find("input#email").val();

            if ( original_email == new_email || original_name == new_name  || new_name == "" || new_email == "" ){
                name.effect( "highlight",  { color: "#F4A4B4" }, 300 );
                email.effect( "highlight", { color: "#F4A4B4" }, 300 );
                return false;
            }
            var data = { name: new_name, email: new_email } ;
            $.ajax( {
              url: "/nueva/alerta/pelicula",
              context: document.body,
              data: data,
              type: "POST",
              success: function( data ){
                 showNotice ( form );
                  form.find("input#name").val( original_name );
                  form.find("input#email").val( original_email );
              },
              statusCode: {
                    200: function(){
                        showNotice ( form );
                    },
                    404: function() {
                        showError(form);
                    },
                    401: function (){
                        showError(form);
                    },
                    406: function (){
                        showError(form);
                    }
                  }

            });
            return false;
        });

        function showNotice ( form ){
            $("p.notice", form.parent(".text") ).show( "slide",  { direction: "down" },  300 ).effect( "highlight", {} , 1300 , endEffect );
        }
        function showError ( form ){
            $("p.error", form.parent(".text") ).show( "slide",  { direction: "down" },  300 ).effect( "highlight", {} , 1300 , endEffect );
        }

        function hideMessages( ){
            if ( $("p.notice", form.parent(".text") ).css("display") == "block" ){
                $("p.notice", form.parent(".text") ).hide("slide", { direction:"down" }, 300 );
            }
            if ( $("p.error", form.parent(".text") ).css("display") == "block" ){
                $("p.error", form.parent(".text") ).hide("slide", { direction:"down" }, 300 );
            }
        }
        function endEffect(){

            setTimeout(function() {
                hideMessages();
            }, 2000 );
        }

        form.find(".wait").hide("slide", { direction: "up" },  300 );
        form.find("input.btn-submit").show( "slide",  { direction: "up" },  300 ) ;



    }

})(jQuery);

/**
 * Plugin for changing recomendations in big front banner
 *
 */
(function($) {
    $.fn.rotateRecommendations = function(options) {
        var _options = jQuery.extend({
            duration:700,
            fade_duration:400,
            step: 1,
            box: $(this),
            first_img: $(this).find("img:first"),
            description_first_image: $(this).find(".description img:first"),
            description_title: $(this).find(".description .text h2"),
            description_links: $(this).find(".description a"),
            description_director: $(this).find(".description .text ul.info li.director"),
            description_stars: $(this).find(".description .text ul.info li.stars"),
            description_genre: $(this).find(".description .text ul.info li.genre"),
            description_duration: $(this).find(".description .text ul.info li.duration")

        }, options);

        $(this).find("a.recommend-other").unbind("click").click(function () {
            activateHold();
            removeDecorators ();
            return false;
        });


        function activateHold(){
            _options.box.find(".list_container").effect( "fade", {}, _options.fade_duration, endEffect );
        }

        function endEffect(){

            setTimeout(function() {
                changeMovie();
                _options.box.find(".list_container").hide().fadeIn();
            }, _options.duration );
        }

        function removeDecorators (){

            if ( _options.box.find("span.decorate").size() > 0 ){
                _options.box.find("span.decorate").fadeOut("fast");
                _options.box.find("span.decorate").remove();
            }
        }

        function changeMovie() {
            _options.step = _options.step + 1;
            if (_options.step > _options.data.length) {
                _options.step = 1;
            }
            var current = _options.data[ _options.step - 1 ];

            if ( current.we_like_it == "true" ){
                var c = $('<span class="decorate" ></span>');
                c.hide();
                _options.box.prepend( c );
                c.effect("slide", { direction: 'right' } , 300 ).effect("shake", { times:2, distance:5 }, 100 );
            }

            _options.first_img.attr("src", current.highlight_image);
            _options.description_first_image.attr("src", current.poster);
            _options.description_title.html(current.title + "(" + current.year + ") ");
            _options.description_links.each(function() {
                if (!$(this).hasClass("recommend-other")) {
                    $(this).attr("href", current.url);
                }
            });
            _options.description_director.html("Dirección: " + current.director);
            _options.description_stars.html("Intérpretes: " + current.stars);
            _options.description_genre.html(current.genre + ".");
            _options.description_duration.html(current.duration);
            
        }

        return this;
    };
})(jQuery);


/**
 * Lading Async Google and Facebook SDK
 *
 *
 */
(function(d) {
    var js, id = 'facebook-jssdk';
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement('script');
    js.id = id;
    js.language="JavaScript";
    js.type="text/javascript";
    js.async = true;
    js.src = "https://connect.facebook.net/es_ES/all.js";
    d.getElementsByTagName('head')[0].appendChild(js);

    
    var g = d.createElement('script');
    g.id = "google-sdk";
    g.language="JavaScript";
    g.type="text/javascript";
    g.async = true;
    g.src = "https://apis.google.com/js/plusone.js";
    d.getElementsByTagName('head')[0].appendChild(g);

    var t = d.createElement("script");
    t.id="twitter-sdk";
    t.async = true;
    t.language="JavaScript";
    t.type="text/javascript";
    t.src= "http://platform.twitter.com/widgets.js";
    d.getElementsByTagName('head')[0].appendChild(t);

    /*
    var tti = d.createElement("script");
    tti.id="twenti-sdk";
    tti.async = true;
    tti.language="JavaScript";
    tti.type="text/javascript";
    tti.src= "http://widgets.tuenti.com/widgets.js";
    d.getElementsByTagName('head')[0].appendChild(tti);
    */
    
}(document));


/**
 * Plugin for save movies for later
 *
 */
(function($) {

    $.fn.saveMovieForLater = function ( options  ){

        var _options = jQuery.extend({}, options);

        var showMessage = function  ( name_class, message ,  object ){
            /*
            if (object.parent("li").find("div").size() > 0 ){
                object.parent("li").find("div").remove();
            }
            */
            var message = $('<div class="see_later_'+name_class+' see_later_canvas">' + message + '</div>');
            //var message = $('<a class="btn01" href="#">'+message+'</a>');
            /*
            message.hide();
            object.parent("li").prepend(message);
            message.show("slide", "fast");
            */
            object.replaceWith(message);
        }
        
        return $(this).live( "click", function (){
            var object = $(this);
            var id = $(this).attr("id");
            $.ajax({
                url: "/ver/mas/tarde/",
                context: document.body,
                data: { "id": id },
                type: "POST",
                success: function( data ){ showMessage("info", "Agregada correctamente", object ); },
                statusCode: {
                    404: function() {
                        showMessage("error", "Inténtalo mas tarde", object);
                    },
                    401: function (){
                        showMessage("error", "Debes estar registrado", object);
                    },
                    406: function (){
                        showMessage("error", "Película ya agregada", object);
                    }
                  }
            });
        });
    };

    $(document).ready(function(){
       $("a[data=save_for_later]").saveMovieForLater({});
    });

})(jQuery);

