// SUBSCRIBE
$(function() {
	function onClick(me, opposite) {
		me.hide();
		$('#subscribe-block .subscribe-loading').show();
		
		$.ajax({
			url: me.attr('href'),
			cache: false,
			dataType: 'json',
			error: function() {
				me.show();
			},
			success: function(data) {
				if (data.result) {
					$('#subscribe-block a').eq(opposite).show();
				} else{
					me.show();
				}
			},
			complete: function() {
				$('#subscribe-block .subscribe-loading').hide();
			}
		});
		
		return false;
	}
	
	$('#subscribe-block a').each(function(idx) {
		$(this).click(function() {
			return onClick($(this), 1 - idx);
		});
	});
});

//BOOKMARKS
$(function() {
	function onClick(me, opposite) {
		me.hide();
		$('#favorite-block .favorite-loading').show();

		$.ajax({
			url: me.attr('href'),
			cache: false,
			dataType: 'json',
			error: function() {
				me.show();
			},
			success: function(data) {
				if (data.result) {
					$('#favorite-block a').eq(opposite).show();
				} else{
					me.show();
				}
			},
			complete: function() {
				$('#favorite-block .favorite-loading').hide();
			}
		});
		
		return false;
	}
	
	$('#favorite-block a').each(function(idx) {
		$(this).click(function() {
			return onClick($(this), 1 - idx);
		});
	});
});

//COMMENTS ADD FORM
$(function () {
	$('#comments-messages .pager a').live('click', function() {
		load($(this).attr('href'));
		return false;
	});

	$('#comment-form-block .action-submit').click(function() {
		$('#comment-form-block form').submit();
		
		return false;
	});
	
	$('#comments-messages .del_comment a').live('click', function() {
		del_comment($(this).attr('href'));
		return false;
	});
	
	function onAjax(data) {
		if (data.result && data.content) {
			$('#comments-messages').html(data.content);
		} else if (data.message){
			alert(data.message);
		} else {
			alert('error');
		}
	}
	
	function load(url) {
		$('#comments-block').block({message:'Loading ...'});
		
		$.ajax({
			'url': url,
			cache: false,
			dataType: 'json',
			error: function() {
				alert('error');
			},
			success: onAjax,
			complete: function() {
				$('#comments-block').unblock();
			}
		});
		
		return false;
	}
	
	function del_comment(url) {
		if (confirm('Delete this comment?')) {
			
			$.ajax({
				type: "POST",
				'url': url,
				error: function() {
					alert('error');
				},
				complete: function() {
					load(url);
				}
			});
		}
		
		return false;
	}
	
	$('#comment-form-block form').ajaxForm({
		method: 'POST',
		dataType: 'json',
		resetForm: true,
		beforeSubmit: function() {
			$('#comments-block').block({message:'Loading ...'});
		},
		success: function(response, result) {
		    if (result == 'success' && typeof response.content != 'undefined') {
		        $('#comments-messages').html(response.content);
		    } else if (result == 'success' && typeof response.login_popup != 'undefined') {
		        var actionUrl = $(this)[0].url;
		        Oauth.setCallback(function(o) {
		            if (o.result) {
		                $.ajax({
	                        type: 'POST',
	                        'url': actionUrl,
	                        cache: false,
	                        dataType: 'json',
	                        error: function() {
	                            alert('error');
	                        },
	                        success: function() {
	                            document.location.href = document.location.href;
	                        },
	                        complete: function() {
	                            $('#comments-block').unblock();
	                        }
	                    }); 
		            }
		        });
		        LoginPopup.setCallback(function(o) {
		            $.ajax({
		                type: 'POST',
		                'url': actionUrl,
		                cache: false,
		                dataType: 'json',
		                error: function() {
		                    alert('error');
		                },
		                success: function() {
		                    document.location.href = document.location.href;
		                },
		                complete: function() {
		                    $('#comments-block').unblock();
		                }
		            });
		        }).show();
		    } else if (typeof response.message != 'undefined') {
		        Notificate.error(response.message);
		    } else {
		        Notificate.error('Error');
		    }
		},
		complete: function() {
			$('#comments-block').unblock();
		}
	});
	
	if ($('#comments-messages a').length > 0) {
		load($('#comments-messages a').attr('href'));
	}
});

// TABS
$(function() {
	$('#tab-block-1').tabs();
	$('#tab-block-2').tabs();
});

// COUNT STATISTICS FOR SOCIAL BOOKMARKS
$(function() {
	$('li.open_social_link a').live('click', function() {		
        $.ajax({
			type: 'POST',
			url: '/en/presentations/increase-social-statistics',
			data: {id : $(this).attr('id')},
			success: function() {		  	
			
			}
		});	
	});
});

// MORE FROT THIS USER
// COUNT STATISTICS FOR SOCIAL BOOKMARKS
$(function() {
    if ($('#moreFromUser .content a').length > 0) {
        changeMoreFromUser($('#moreFromUser .content a').attr('href'));
    }
	
	$('#moreFromUser .content .pager a').live('click', function() {
		changeMoreFromUser($(this).attr('href'));
		return false;
	});
});

function changeMoreFromUser(url) {
	$('#moreFromUser .content').block({message:'Loading ...',applyPlatformOpacityRules: false});
	$.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        error: function() {
            this.reportRequestError(data.message);
        },
        success: function(data) {
            $('#moreFromUser .content').html(data.content);
        },
        complete: function() {
            $('#moreFromUser .content').unblock();
        }
    });
}

var Presentation = {
    contentUrl: null,
    
    pid: null,
    
    title: null,
    
    lang: null,
    
    dialogInited: false,
    
    btnTag: '<a name="SP_share_btn" type="SP_btn_#TYPE#" id="SP_presentation_#ID#" lang="#LANG#" autoplay="#AUTOPLAY#" title="#TITLE#"#ATTRS#></a>' +
            "\n" + 
            '<script type="text/javascript" src="#BASE_URL#/js/share_btn/buttons.js"></script>',
            
    selectedBtn: null,
    
    buttons: null,
    
    init: function(options) {
        this.setOptions(options);
        this.buttons = [];
        var self = this;
        
        $('#embeding-overlay').jqm({
            ajax: self.contentUrl,
            toTop: true,
            onLoad: function(h) {
                self.initDialog();
            }
        });
        
        $('#embed-presentation-btn').live('click', function(e) {
            e.preventDefault();
            $('#embeding-overlay').jqmShow();
        });
        
        $('#embeding-player-auto').live('click', function() {
            self.setEmbedTag();
        });
        
        $('#embeding-btn-auto').live('click', function() {
            if (self.selectedBtn) {
                self.setBtnTag();
            }
        });
        
        $('.sp-btn-item').live('click', function(e) {
            e.preventDefault();
            self.onClick(this);
        });
    },
    
    setOptions: function(options) {
        if (typeof options.contentUrl != 'undefined') {
            this.contentUrl = options.contentUrl;
        }
        if (typeof options.pid != 'undefined') {
            this.pid = options.pid;
        }
        if (typeof options.title != 'undefined') {
            this.title = options.title;
        }
        if (typeof options.lang != 'undefined') {
            this.lang = options.lang;
        }
    },
    
    initDialog: function() {
        $('a.widget-info-button').tooltip({width: 300});
        $('#embeding-player-clipboard').clipboard({
            width: 140,
            height: 18,
            html_text: '<span class="clipboard-btn">Copy to clipboard</span>',
            style_sheet: '.clipboard-btn {text-decoration: underline; color: #4D6582; font-family: Tahoma,Arial,Helvetica,sans-serif; background: url(/images/clipboard-icon.png)}',
            movie: '/flash/clipro.swf',
            callback: function() {
                return $('#embeding-player-code').attr('value');
            }
        });
        
        $('#embeding-btn-clipboard').clipboard({
            width: 140,
            height: 18,
            html_text: '<span class="clipboard-btn">Copy to clipboard</span>',
            style_sheet: '.clipboard-btn {text-decoration: underline; color: #4D6582; font-family: Tahoma,Arial,Helvetica,sans-serif; background: url(/images/clipboard-icon.png)}',
            movie: '/flash/clipro.swf',
            callback: function() {
                return $('#embeding-btn-code').attr('value');
            }
        });
        
        this.setEmbedTag();
        
        this.widgets = $('#scroll-box').scrollable({
            mousewheel: true,
            items: '.scroll-box-items',
            next: '.scroll-box-next',
            prev: '.scroll-box-prev',
            vertical: true
        }).data('scrollable');
        
        this.addItems();
    },
    
    addItems: function() {
        var rowDiv = $('<div></div>').attr('class', 'sp-btn-row');
        var icnt = 0;
        var self = this;
        var rowAdded;
        
        for (var i in SlidePresenterConfig.buttons) {
            
            if (!SlidePresenterConfig.buttons[i].enabled ||
                 i == 'flash' ||
                 i == 'embed') {
                
                continue;
            }
            
            rowAdded = false;
            
            var item = $('<a></a>').attr('name', SlidePresenterConfig.btnName)
                        .attr('id', 'SP_btn_example_' + this.buttons.length)
                        .html(SlidePresenterConfig.buttons[i].inner.replace(/#ID_SPEC#/g, SlidePresenter.getIdSpec(this.pid)).replace(/#BASE_URL#/g, SlidePresenterConfig.baseUrl));
            
            // Align verticaly
            var marginTop = (170 - parseInt(SlidePresenterConfig.buttons[i].css.height)) / 2;
            SlidePresenterConfig.buttons[i].css.margin = marginTop + 'px 0 0 0';
            
            this.setStyles(item, SlidePresenterConfig.buttons[i].css);
            
            var newDiv = $('<div></div>').attr('class', 'sp-btn-item').append(item);
            
            rowDiv.append(newDiv);
            
            this.buttons[this.buttons.length] = {
                    element: item,
                    type: i,
                    hover: SlidePresenterConfig.buttons[i].hover,
                    css: SlidePresenterConfig.buttons[i].css
            };
            
            icnt++;
            if (icnt == 2 || i == SlidePresenterConfig.buttons.length - 1) {
                rowDiv.append($('<span></span>').attr('class', 'clear'));
                this.widgets.addItem(rowDiv);
                rowDiv = $('<div></div>').attr('class', 'sp-btn-row');
                icnt = 0;
                rowAdded = true;
            }
        }
        if (!rowAdded) {
            rowDiv.append($('<span></span>').attr('class', 'clear'));
            this.widgets.addItem(rowDiv);
        }
    },
    
    setStyles: function(el, styles) {
        $.each(styles, function(name, value) {
            el.css(name, value);
        });
    },
    
    setEmbedTag: function() {
        var tag;
        
        tag = this.btnTag.replace(/#ID#/g, this.pid);
        tag = tag.replace(/#LANG#/g, this.lang);
        tag = tag.replace(/#TITLE#/g, this.title);
        tag = tag.replace(/#TYPE#/g, 'embed');
        tag = tag.replace(/#AUTOPLAY#/g, $('#embeding-player-auto').attr('checked') ? 1 : 0);
        tag = tag.replace(/#BASE_URL#/g, SlidePresenterConfig.baseUrl);
        tag = tag.replace(/#ATTRS#/g, '');
        
        $('#embeding-player-code').attr('value', tag);
    },
    
    setBtnTag: function() {
        var tag;
        
        tag = this.btnTag.replace(/#ID#/g, this.pid);
        tag = tag.replace(/#LANG#/g, this.lang);
        tag = tag.replace(/#TITLE#/g, this.title);
        tag = tag.replace(/#TYPE#/g, this.buttons[this.selectedBtn].type);
        tag = tag.replace(/#AUTOPLAY#/g, $('#embeding-btn-auto').attr('checked') ? 1 : 0);
        tag = tag.replace(/#BASE_URL#/g, SlidePresenterConfig.baseUrl);
        tag = tag.replace(/#ATTRS#/g, '');
        
        $('#embeding-btn-code').attr('value', tag);
    },
    
    onClick: function(el) {
        var index = $(el.children).attr('id').match(/\d+$/)[0];
        var self  = this;
        $('.sp-btn-item').each(function(num, item) {
            if (num == index) {
                $(item).addClass('selected');
                self.selectedBtn = index;
            } else {
                $(item).removeClass('selected');
            }
        });
        this.setBtnTag();
    },
    
    onMouseOver: function(el) {
        var index = $(el).attr('id').match(/\d+$/)[0];
        
        if (this.buttons[index].hover != null) {
            this.setStyles($(el), this.buttons[index].hover);
        }
    },
    
    onMouseOut: function(el) {
        var index = $(el).attr('id').match(/\d+$/)[0];
        
        if (this.buttons[index].hover != null) {
            this.setStyles($(el), this.buttons[index].css);
        }
    }
};

