$(document).ready(function() {
    
	$(".open_modal").colorbox({opacity: 0.2, close: ' ', innerHeight: 315, innerWidth: 428});
    
    /**************** GO TO TOP/PLAYER *********************/
    
    $("a.go-to-top").click(function(){
	     $("html, body").animate({scrollTop: "0px"}, 1000);
	     return false;
	});
    
    $("a.play-pasaj").click(function(){
    	$('html,body').animate({scrollTop: $("#player").offset().top}, 2000);
	     return false;
	});

    /******************USER MENU**********************/
    $('#userMenu').hover(
        function () {
                $('#userMenu li a.myAccount').addClass('myAccountActive');
                $('#userDropdownUl').show();

        },
        function () {
                $('#userMenu li a.myAccount').removeClass('myAccountActive');
                $('#userDropdownUl').hide();
        }
    );
    
    $('#resurse_favorite_select').change(function() {
        $("#filter_value").val("");
        $('#filter').submit();
        return false;
    });

    $('#carte').change(function() {
        $("#filter_value").val("");
        $('#resources_reference_navigation_book').submit();
        return false;
    });

    $('#capitol').change(function() {
        $('#resources_reference_navigation_chapter').submit();
        return false;
    });

    /* handle the mouse over cursor when hovering next, previous */
    $('#next_acelasi_autor').live('mouseover', (function() {
        $(this).css("cursor", "pointer");
    }));

    $('#previous_acelasi_autor').live('mouseover', (function() {
        $(this).css("cursor", "pointer");
    }));

    $('#next_acelasi_album').live('mouseover', (function() {
        $(this).css("cursor", "pointer");
    }));

    $('#previous_acelasi_album').live('mouseover', (function() {
        $(this).css("cursor", "pointer");
    }));

	$('#clear_date_res_daily').click(function() {
		$('#date_resources_daily').attr("value", "");
		$('#filter').submit();
	});
	
    $('#res_act_show_comentarii').click(function() {
        $('#add_comentarii').hide();
        $('#res_problems').hide();
        $('#raspuns_adaugare').hide();
        $('#rasp_nepotrivit').hide();
        $('#comentarii').show();
        $('.activeButton').removeClass("activeButton");
        $('#res_act_show_comentarii').addClass("activeButton");
    });

    $('#res_act_add_comentariu').click(function() {
        $('#add_comentarii').show();
        $('#comentarii').show();
        $('#res_problems').hide();
        $('#raspuns_adaugare').hide();
        $('.activeButton').removeClass("activeButton");
        $('#res_act_add_comentariu').addClass("activeButton");
        $('#rasp_nepotrivit').hide();
    });

    $('#res_act_probleme').click(function() {
        $('#comentarii').hide();
        $('#add_comentarii').hide();
        $('#res_problems').show();
        $('#rasp_nepotrivit').hide();
        $('#raspuns_adaugare').hide();
        $('.activeButton').removeClass("activeButton");
        $('#res_act_probleme').addClass("activeButton");
    });

    $('#cele_mai_trimise').click(function() {
        $('#ultimele_felicitari').hide();
        $('#cele_mai_trimise_felicitari').show();

        $('#ultimele').removeClass("bgOrangeTitle");
        $('#cele_mai_trimise').addClass("bgOrangeTitle");
    })
    $('#ultimele').click(function() {
        $('#cele_mai_trimise_felicitari').hide();
        $('#ultimele_felicitari').show();

        $('#cele_mai_trimise').removeClass("bgOrangeTitle");
        $('#ultimele').addClass("bgOrangeTitle");

    })

    $(':regex(id,^resource_delete([0-9])+$)').click(function() {
        var strid = this.id;
        var matches = strid.match(/([0-9]+)/g);
        var id = matches[0]

        if (confirm('Sunteti sigur ca doriti stergerea acestei resurse?')) {

        }
        $('#comentarii').load("/ajax/load-comments",
        {
            page: page_nr,
            res_id: $('#resource_id').val()
        },
        function(responseText, textStatus, XMLHttpRequest) {

            }
            );
    });

    $('#popup_audio_player').click(function() {
        var recipe =  window.open('',''+Math.floor(Math.random()*11)+'','width=775,height=320,toolbar=0,location=0');
        //        $('#recipe1').clone().appendTo('#myprintrecipe');
        var html = "<html><head><title>Player www.resursecrestine.ro</title></head><body><div id=\"player2\"></div></body></html>";
        recipe.document.open();
        recipe.document.write(html);
        recipe.document.close();
        recipe.document.getElementById('player2').appendChild(document.getElementById('player'));
        recipe = null;
        return false;
    });
    
    $('#cauta_button').click(function() {
    	if ('' == $('#search_text').val()) {
    		alert('Introduceti un text pentru cautare.');
    		return false;
    	}
    	
    	return true;
    });

    $('#search_in').change(function() {
    	// change the search_by combobox
    	set_search_by_options(false);
    });
    
    $('#search_in').ready(function() {
    	// change the search_by combobox
    	var field = $('#search_by_field').val();
    	set_search_by_options(field);
    });
    
	
    $("#apiVerse").click(function () {
            highlight($(this));
    });

     $("#apiRCWS").click(function () {
            highlight($(this));
    });
     
     
    $("#show_reference").click(function() {
			var text = $("#reference_wrapper:visible").size() > 0 ? ' + Citeste referinta' : ' - Ascunde referinta';
			$("#reference_wrapper").toggle();
			$(this).html(text);
			return false;
	});
     

     // VIZUALIZARE ONLINE
     var activeOnline = 0;
     $('.view-online').click(function() {
        var link_id = $(this).attr('id');
        var id = link_id.substr(5, link_id.length);
        closeActiveOnlineOrDownload(activeOnline, activeDownload);
        activeOnline = id;
        $('#' + link_id).hide();
        $('#loading_' + id).show();
        $.ajax({
            type: "POST",
            url: "/ajax/render-embedded-video",
            data: "id=" + id,
            success: function(data){
               $('#resource_' + id).append(data);
               $('#loading_' + id).hide();
               $('#close_' + id).css('display', 'inline-block');
            }
        });

        return false;
    });

     $('.close-online').click(function() {
        var link_id = $(this).attr('id');
        var id = link_id.substr(6, link_id.length);
        $('#embedded_video_code').remove();
        $('#' + link_id).hide();
        $('#view_' + id).show();
        activeOnline = 0;
        return false;
    });
     
    //DOWNLOAD FROM LIST
     var activeDownload = 0;
     $('.download-from-list').click(function() {
        var link_id = $(this).attr('id');
        var id = link_id.substr(9, link_id.length);
        closeActiveOnlineOrDownload(activeOnline, activeDownload);
        activeDownload = id;
        $('#' + link_id).hide();
        $('#loading_download_' + id).show();
        $.ajax({
            type: "POST",
            url: "/ajax/download-from-list",
            data: "id=" + id,
            success: function(data){
               $('#resource_' + id).append(data);
               $('#loading_download_' + id).hide();
               $('#close_download_' + id).css('display', 'inline-block');
            }
        });

        return false;
    });

     $('.close-download').click(function() {
        var link_id = $(this).attr('id');
        var id = link_id.substr(15, link_id.length);
        $('#download_code').remove();
        $('#' + link_id).hide();
        $('#download_' + id).show();
        activeDownload = 0;
        return false;
    });

     function highlight(elemId){
	    var elem = $(elemId);
	    elem.children(".continut-verset").css("font-weight", "bold"); // hack for Safari
	    elem.next().children(".versetText").css("font-weight", "bold"); // hack for Safari
	    }
	   
	if (document.location.hash) {
	    highlight(document.location.hash);
	}
	
	jQuery( "#textsizer-classnames a" ).textresizer({
		target: ".resized-text, .bible-resized-text",
		type: "cssClass",
		sizes: [
		        "small-text", 
		        "medium-text", 
		        "large-text" 
		        ],
		selectedIndex: 0
	});
	
	$('.link-confirm-rel-res').click(function () {
		var resource_id = $('#resource_id').val();
		var linked_resource_id = $(this).attr('rel');
		var elemObj = $(this);

		$.ajax({
		    type: "POST",
		    url: "/ajax/confirm-related-resource",
		    data: {
		        resource_id: resource_id,
		        linked_resource_id: linked_resource_id
		    },
		    dataType: 'json',
		    success: function (data) {
		        if (data.status_code == 'SUCCESS') {

			        if (data.accept == true) {
			        	elemObj.removeClass('confirma-resurse').addClass('anuleaza-resurse');
			        }
			        else {
			        	elemObj.removeClass('anuleaza-resurse').addClass('confirma-resurse');
			        }    
		        	
		        }
		        else {
			        alert(data.error);
		        }
		    }
		});

		return false;
	});

	$("div.tab").hide();
	$(".tabs li a.active").each(function(){
		var activeTab = $(this).attr("rel");
		$("#"+activeTab).show();
	});

	$(".tabs a").click(function(){
		var firstHref = $(this).attr("href").substr(0,1);
		if (firstHref=="#") {
			switchTab(this);
			return false;
		}
	});
	
	
});

function closeActiveOnlineOrDownload(activeOnline, activeDownload) {
    if(activeOnline != 0) {
        $('#embedded_video_code').remove();
        $('#close_' + activeOnline).hide();
        $('#view_' + activeOnline).show();
    }
    if(activeDownload != 0) {
        $('#download_code').remove();
        $('#close_download_' + activeDownload).hide();
        $('#download_' + activeDownload).show();
    }
}

function highlight(element) {
	element.focus();
	element.select();
}

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
    validLabels = /^(data|css):/,
    attr = {
        method: matchParams[0].match(validLabels) ?
        matchParams[0].split(':')[0] : 'attr',
        property: matchParams.shift().replace(validLabels,'')
    },
    regexFlags = 'ig',
    regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

function fillReferenceChapter(index) {
	var book_index = $('select#new_reference_' + index + '_book').val();
	$.ajax({
        type: "POST",
        url: "/ajax/fill-reference-chapter",
        dataType: 'json',
        data: "book_index=" + book_index,
        success: function(j) {
			var options = '<option value="0">Capitol inceput</option>';
			var options1 = '<option value="0">Capitol sfarsit</option>';
	        for (var i = 1; i <= j.number; i++) {
	            options += '<option value="' + i + '">' + i + '</option>';
	            options1 += '<option value="' + i + '">' + i + '</option>';
	        }
	        $('select#new_reference_' + index + '_start_chapter').html(options);
	        
	        $('select#new_reference_' + index + '_end_chapter').html(options1);
	        
	        options = '<option value="0">Verset inceput</option>';
	        $('select#new_reference_' + index + '_start_verse').html(options);
	        
	        options = '<option value="0">Verset sfarsit</option>';
	        $('select#new_reference_' + index + '_end_verse').html(options);
        }
    });
}

function fillReferenceVerseFrom(index) {
	var book_index = $('select#new_reference_' + index + '_book').val();
	var chapter = $('select#new_reference_' + index + '_start_chapter').val();
	$.ajax({
        type: "POST",
        url: "/ajax/fill-reference-verse",
        dataType: 'json',
        data: { book_index :  book_index, chapter: chapter},
        success: function(j) {
			var options = '<option value="0">Verset inceput</option>';
	        for (var i = 1; i <= j.number; i++) {
	            options += '<option value="' + i + '">' + i + '</option>';
	        }
	        $('select#new_reference_' + index + '_start_verse').html(options);
        }
    });
}

function fillReferenceVerseTo(index) {
	var book_index = $('select#new_reference_' + index + '_book').val();
	var chapter = $('select#new_reference_' + index + '_end_chapter').val();
	$.ajax({
        type: "POST",
        url: "/ajax/fill-reference-verse",
        dataType: 'json',
        data: { book_index :  book_index, chapter: chapter},
        success: function(j) {
	        options = '<option value="0">Verset sfarsit</option>';
	        for (var i = 1; i <= j.number; i++) {
	            options += '<option value="' + i + '">' + i + '</option>';
	        }
	        $('select#new_reference_' + index + '_end_verse').html(options);
        }
    });
}

function fillChapter(index) {
	var book_index = $('select#search_intrebari_concurs_book').val();
	$.ajax({
        type: "POST",
        url: "/ajax/fill-reference-chapter",
        dataType: 'json',
        data: "book_index=" + book_index,
        success: function(j) {
			var options = '<option value="0"></option>';
	        for (var i = 1; i <= j.number; i++) {
	            options += '<option value="' + i + '">' + i + '</option>';
	            
	        }
	        $('select#search_intrebari_concurs_chapter').html(options);
	        options = '<option value="0"></option>';
	        $('select#search_intrebari_concurs_verse').html(options);
        }
    });
}

function fillVerse(index) {
	var book_index = $('select#search_intrebari_concurs_book').val();
	var chapter = $('select#search_intrebari_concurs_chapter').val();
	$.ajax({
        type: "POST",
        url: "/ajax/fill-reference-verse",
        dataType: 'json',
        data: { book_index :  book_index, chapter: chapter},
        success: function(j) {
			var options = '<option value="0"></option>';
	        for (var i = 1; i <= j.number; i++) {
	            options += '<option value="' + i + '">' + i + '</option>';
	        }
	        $('select#search_intrebari_concurs_verse').html(options);
        }
    });
}

function saveNewCategory() {
	var res_type_id =  $('#resource_res_type_id').val();
	var reply = prompt("Introduceti un nume", "")
	if (reply) {
		$.ajax({
	        type: "POST",
	        url: "/ajax/new-category",
	        dataType: 'json',
	        data: { name :  reply,  res_type_id: res_type_id },
	        success: function(j) {
	        	 var options = ''; 
	        	 var opt = j.options;
	        	 for (var i = 0; i < opt.length; i++) {
	                    options += '<option value="' + opt[i].optionValue + '">' + opt[i].optionDisplay + '</option>';
	                }
		        $('select#resources_res_category_id').html(options);
		        $("#resources_res_category_id option[value='" + j.selectedOption + "']").attr('selected', 'selected');
	        }
	    });
	}
}


function set_search_by_options(sel) {
	var val = $('#search_in').val();
	var old_selection = 1;
	if (val == 16) { // Bible
		$("#search_by").children().remove();
		$('#search_by').append('<option value="filtru-versete">Versete</option>');
	}
	else if (val == 36) { //Stiri
		$("#search_by").children().remove();
		$('#search_by').append('<option value="filtru-titlu">Titlu</option>');
		$('#search_by').append('<option value="filtru-autor">Autor</option>');
		$('#search_by').append('<option value="filtru-continut">Continut</option>');
	}
	else if (val == 0) {
    	$("#search_by").children().remove();
		$('#search_by').append('<option value="filtru-titlu">Titlu</option>');
		$('#search_by').append('<option value="filtru-autor">Autor</option>');
		$('#search_by').append('<option value="filtru-album">Album/Volum</option>');
	}
	else{
		$("#search_by").children().remove();
		$('#search_by').append('<option value="filtru-titlu">Titlu</option>');
		$('#search_by').append('<option value="filtru-autor">Autor</option>');
		$('#search_by').append('<option value="filtru-album">Album/Volum</option>');
		$('#search_by').append('<option value="filtru-continut">Continut</option>');
	}
	
	if (sel != false) {
		$('#search_by option[value=' + sel + ']').attr('selected', 'selected');

	}
}

function previewResource(domain, url) {
	var height = 550;
	if (domain == 'audio') {
		height = 200;
	}
	$.colorbox({
		opacity: 0.2, 
		close: ' ', 
		iframe: true,
		href: url,
		innerWidth: 580, innerHeight: height
	});
}

function switchTab(elem) 
{
	$(elem).parent().parent().parent().find(".tabs li a").removeClass("active");
	$(elem).addClass("active");
	var thisElementName = $(elem).attr("rel");
	$(elem).parent().parent().parent().find("div.tab").hide();
	$("#" + thisElementName).show();
}

function progressBar(id, total, actual) {
	var percent = Math.round(100*actual/total);
	var time = 50*percent;
	$(id).find('.progress-value').animate({width: percent + "%"}, time);
	$(id).find('.progress-text').delay(time).fadeIn(500);
}

function resReferences(ID){
	$(ID).click(function(){
		if ($(ID).hasClass('ref-down')) {
			$(ID).removeClass('ref-down').addClass('ref-up');
			$('#animateBox').animate({'height':'175px'}, 500);
			$('#hid').delay(500).fadeIn(500);
		} else {
				$(ID).removeClass('ref-up').addClass('ref-down');
				$('#hid').fadeOut(500);
				$('#animateBox').delay(500).animate({'height':'26px'}, 500);
			}
		}
)}

/********** CLIPBOARD VERSET **********/

function versetClipboard(){
	var clip = new ZeroClipboard.Client();
	ZeroClipboard.setMoviePath('/js/ZeroClipboard10.swf');          
	clip.setText('');
	clip.setHandCursor(true);
	clip.setCSSEffects(true);
	
	clip.addEventListener( 'mouseDown', function(client) { 
		clip.setText(document.getElementById('clipboard').value);
	} );
	
	clip.addEventListener( 'mouseOver', function(client) { 
		document.getElementById('copy').style.backgroundPosition='-260px -760px';
	} );
	
	clip.addEventListener( 'mouseOut', function(client) { 
		document.getElementById('copy').style.backgroundPosition='-260px -740px';
	} );
	
	clip.glue('copy');
}

/********** POPUP VERSET **********/

function meniuVerset() {
	$('li.versetWrapper').click(function(e) {
			
		var verset_id = $(this).attr('id');
		verset_id = verset_id.substr(7);
		var element = $(this);
		
		var x = e.pageX-element.offset().left-110;
		
		var iX = 523;
		var Lay = String(document.location);
		var LayDiv = document.getElementById("verslist");
		var LayDivWidth = LayDiv.offsetWidth;
		if (Lay.search("external")!=-1)
			iX = LayDivWidth-220;
		
		if (x < 0) {
			x = 0;
		} else if (x > iX) {
			x = iX;
		}
					
		var meniuPos = element.position();
	    	element.toggleClass('verset-activ');
		    	if (element.hasClass('verset-activ')) {
		    		if ($('li#verset-options').hasClass('meniu-activ')) {
		    			$('li#verset-options').animate({'top': meniuPos.top-65+'px', 'left': x+'px'});
		    			$('#copy-con').remove();
		    			$.ajax({
				    		type: "POST",
				    		dataType: 'json',
				    		url: "/ajax/get-verset-tooltip",
				    		data: { id : verset_id },
				    		success: function(data) {
				    			$('#verset-options .inner-verset-option').html(data.content);
				    		}
				    	});
		    		} else {
		    			$('li#verset-options').css({'top': meniuPos.top-65+'px', 'left': x+'px'}).fadeIn(200).addClass('meniu-activ');
		    			$('#copy-con').remove();
		    			$.ajax({
				    		type: "POST",
				    		dataType: 'json',
				    		url: "/ajax/get-verset-tooltip",
				    		data: { id : verset_id },
				    		success: function(data) {
				    			$('#verset-options .inner-verset-option').html(data.content);
				    		}
				    	});
		    		};
		    	} else {
		    		$('#copy-con').remove();
		    		$('li#verset-options').removeClass('meniu-activ').fadeOut(300);
		    	};
		    	element.siblings().removeClass('verset-activ');
		});
	}

function CommentsPending(HoverDiv, CommentsDiv) {
	var el = $(HoverDiv);
	var Pos = el.position();
	$(HoverDiv).hover(function() {
		$(HoverDiv).click(function() {
			$(CommentsDiv).show();
			$(CommentsDiv).css({'top': Pos.top-133+'px'});
		});
	}, function() {
		$(CommentsDiv).hover( function() {
		$(CommentsDiv).show();
		$(HoverDiv).addClass("active");
		}, function() {
			$(CommentsDiv).hide();
			$(HoverDiv).removeClass("active");
		});
		$(CommentsDiv).hide();
	});
}

function flagResource(HoverDiv, CommentsDiv, CancelButton) {
	var el = $(HoverDiv);
	var Pos = el.position();
	fc = false;
	$(HoverDiv).hover(function() {
		$(HoverDiv).click(function() {
			$(CommentsDiv).show();
			$(CommentsDiv).css({'top': Pos.top-128+'px', 'left': Pos.left-104+'px'});
		});
	}, function() {
		$(CommentsDiv).hover( function() {
		$(CommentsDiv).show();
		$(HoverDiv).addClass("active");
		}, function() {
			
			$('.comentariu-flag')
	        .focus(function(){
	            fc = true;
	        })
	        .blur(function(){
	            fc = false;
	        });
			
			if (fc == false) {
				$(CommentsDiv).hide();
				$(HoverDiv).removeClass("active");
			}
			
		});
		$(CommentsDiv).hide();
		});
	
	$(CancelButton).click(function() {
		$(CommentsDiv).hide();
	});
}

/***************************************************************/
