function scrollToElement(elementId, paddingTop) {
	var element = $("#" + elementId);
	if (element != null) {
		$('html, body').animate({scrollTop:element.offset().top - paddingTop}, 0);
	}
	return false;
}

function bbEditorPreview(isEdit) {
        var userId="";
        if(isEdit){
            userId= $("#previewUserId").val();
        }
        $.post(env.FORUM_POST_PREVIEW, {bbCode:$("#bbEditor").val(),"userId":userId},
            function(data){
                var text = $(data).filter('#postAjaxPreview');
                $("#previewBody").html(text.html());
                if(isEdit){ 
                    var avatar = $(data).filter('#postPreviewAvatarId');
                    $("#prevAvatar").remove();
                    if(avatar.length){
                        $("#prevDiv").before(avatar.html());
                    }
                    $("#prevAuthor").html($("#previewUserName").val());
                }
                $("#editorPreview").show();
                scrollToElement("bbEditor", 100);
            });
}

function htmlToBbCode(html) {
	function rep(a, b) {
		html = html.replace(a, b);
	}
	rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]");
	//rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
	//rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
	//rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
	//rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
	//rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi,"[color=$1]$2[/color]");
	//rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[color=$1]$2[/color]");
	//rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi,"[size=$1]$2[/size]");
	//rep(/<font>(.*?)<\/font>/gi,"$1");
	rep(/<img.*?src=\"(.*?)\".*?\/>/gi,"[img]$1[/img]");
	rep(/<img.*?src=\"(.*?)\".*?>/gi,"[img]$1[/img]");
	rep(/<\/(strong|b)>/gi,"[/b]");
	rep(/<(strong|b)>/gi,"[b]");
	rep(/<\/(em|i)>/gi,"[/i]");
	rep(/<(em|i)>/gi,"[i]");
	rep(/<\/u>/gi,"[/u]");
	rep(/<u>/gi,"[u]");
	//rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi,"[u]$1[/u]");
	rep(/<ul[^>]*>/gi,"[ul]");
	rep(/<\/ul>/gi,"[/ul]");
	rep(/<li[^>]*>/gi,"[li]");
	rep(/<\/li>/gi,"[/li]");
	
	rep(/<tr[^>]*>/gi,"[tr]");
     rep(/<\/tr>/gi,"[/tr]");
     rep(/<td[^>]*>/gi,"[td]");
     rep(/<\/td>/gi,"[/td]");
     rep(/<table[^>]*>/gi,"[table]");
     rep(/<\/table>/gi,"[/table]");
     rep(/<tbody[^>]*>/gi,"");
     rep(/<\/tbody>/gi,"");
	
	rep(/<blockquote[^>]*>/gi,"[quote]");
	rep(/<\/blockquote>/gi,"[/quote]");
	rep(/<br \/>/gi,"\n");
	rep(/<br\/>/gi,"\n");
	rep(/<br>/gi,"\n");
	rep(/<p>/gi,"");
	rep(/<\/p>/gi,"\n");
	rep(/&nbsp;/gi," ");
	rep(/&quot;/gi,"\"");
	rep(/&lt;/gi,"<");
	rep(/&gt;/gi,">");
	rep(/&amp;/gi,"&");
	return html;
}

function bbCodeToHtml(bbCode) {
	function rep(a, b) {
		bbCode = bbCode.replace(a, b);
	}
	rep(/&/g,"&amp;");
	rep(/</g,"&lt;");
	rep(/>/g,"&gt;");
	rep(/\n/g, "<br />");
	rep(/\[b\]/g, "<b>");
	rep(/\[\/b\]/g, "</b>");
	rep(/\[i\]/g, "<i>");
	rep(/\[\/i\]/g, "</i>");
	rep(/\[u\]/g, "<u>");
	rep(/\[\/u\]/g, "</u>");
	rep(/\[ul\]/g, "<ul>");
	rep(/\[\/ul\]/g, "</ul>");
	rep(/\[li\]/g, "<li>");
	rep(/\[\/li\]/g, "</li>");
	rep(/\[url=([^\]]+)\](.*?)\[\/url\]/g,'<a href="$1" target="_blank">$2</a>');
	rep(/\[url\](.*?)\[\/url\]/g, '<a href="$1" target="_blank">$1</a>');
	rep(/\[img\](.*?)\[\/img\]/g, '<img src="$1" />');
	//rep(/\[color=(.*?)\](.*?)\[\/color\]/g,'<font color="$1">$2</font>');
	rep(/\[code\](.*?)\[\/code\]/g,'<span class="codeStyle">$1</span>&nbsp;');
	rep(/\[quote=(.*?)\]/g, "<blockquote><b>$1</b><br />");
	rep(/\[quote\]/g, "<blockquote>");
	rep(/\[\/quote\]/g, "</blockquote>&nbsp;");
	return bbCode;
}

function rankPost(threadId, postId, ranking) {
	$.ajax({
		url: env.FORUM_POST_RANK,
		dataType: "json",
        data: {
			threadId: threadId,
            postId: postId,
            ranking: ranking
        },
        cache: false,
        success: function(data){
        	var like = $("#like_" + postId);
        	var dislike = $("#dislike_" + postId);
        	
        	if (data.ranking == 1) {
        		like.addClass("ico-thumbsup-selected");
        		dislike.removeClass("ico-thumbsdown-selected");
        	} else if (data.ranking == 0) {
        		like.removeClass("ico-thumbsup-selected");
        		dislike.removeClass("ico-thumbsdown-selected");
        	} else if (data.ranking == -1) {
        		like.removeClass("ico-thumbsup-selected");
        		dislike.addClass("ico-thumbsdown-selected");
        	}

        	var likes = $("#post_stats_" + postId).find(".likes")[0];
        	var dislikes = $("#post_stats_" + postId).find(".dislikes")[0];
        	
        	likes.style.width = data.likeFactor + "%";
        	dislikes.style.width = data.dislikeFactor + "%";
        	
        	$(likes).attr("title", data.likeCount);
        	$(dislikes).attr("title", data.dislikeCount);
        }
    });
	return false;
}

function selectTop(column, topType) {
	if ($(column).attr("class") == "active") {
		return;
	}
	
	$.ajax({
		type: 'GET',
		data: {'topType': topType},
		url: env.FORUM_TOP,
		cache: false,
        success: function(data) {
			$(".forum-toplist-content").html(data);

			var strongToReplace = $(".tabs-small li.active").find("strong")[0];
			$(strongToReplace).replaceWith("<a href='#'>" + strongToReplace.innerHTML + "</a>");	
			$(".tabs-small li.active").removeClass("active");
			
			var aToReplace = $(column).find("a")[0];
			$(aToReplace).replaceWith("<strong>" + aToReplace.innerHTML + "</strong>");
			$(column).addClass("active");
        }
	});
}

function scrollNews(isAnalyses, direction) {
	$.ajax({
		type: 'GET',
		data: {'id': $.find("#securityId")[0].value, 
			   'dir': direction,
		       'analysesPage': $.find("#analysesPage")[0].value, 
			   'announcesPage': $.find("#announcesPage")[0].value, 
			   'isAnalyses': isAnalyses},
		url: env.COMPANY_VIEW_NEWS,
		cache: false,
        success: function(data) {
			$("#newsblock").html(data);
        }
	});
}

function reportAbuse() {
    $.ajax({ 
        type: 'GET', 
        data: { 
        	'postId': $('#postToReportOf').val(),
        	'threadId': $('#threadOfPost').val()
        }, 
        url: env.FORUM_REPORT_ABUSE,
        cache: false
    });
}

function replaceContainerAsync(url, containerId){
    $("#"+containerId).load(url, function() {
        scrollToElement(containerId, 100);
    });
}

function replaceContainerAndFade(url, containerId) {
	var $dataDiv = $("#"+containerId);
	$dataDiv.fadeTo(200, 0, function() {
		$dataDiv.load(url, function() {
			$dataDiv.fadeTo(200, 1);
		});
	});
}

function getThreadAjax(threadId,topic,headerId, containerId,postId,command){
    
    if(threadId==""){
        return false;
    }
    if(command == ""){
        command="ajax";
    }
    
    $.ajax({
      url: env.FORUM_THREAD_VIEW,
      data: {
          threadId: threadId,
          topic: topic,
          containerId: containerId,
          ajax: command,
          postId:postId
      },
      cache: false,
      success: function(data){

        $("#"+headerId).empty().append("<h1>"+env.NEWS_VIEW_COMMENTS+"</h1>");
        $("#"+containerId).html(data);
        
        if($('#scrollToPost').length){
            scrollToElement($('#scrollToPost').val(), 10);
        }else if(command =="scroll"){
            scrollToElement("news_comments", 10);
        }
      },
      error: function(data){
          $("#"+headerId).empty().append("<h2 id='news_comments_header'>"+env.NEWS_VIEW_NO_COMMENTS+"</h2>");
      }
  });
   return false;
}

function ajaxChangeNickname(ajaxErrMsg) {
    $.ajax({
      url: env.CHANGE_NICKNAME_AJAX,
      data: {
          newNickname: document.getElementById('newNickname').value
      },
      cache: false,
      error: function(data) {
    	  alert(ajaxErrMsg);
      },
      success: function(data) {
    	  if (!data) {
    		  document.getElementById("editorView").submit();
    	  } else {
    		  alert(data);
    	  }
      }
	});
}

function resizeImage(elem, maxWidth, maxHeight) {
    var ratio = 0;  // Used for aspect ratio
    var width = $(elem).width();    // Current image width
    var height = $(elem).height();  // Current image height
    
    // Check if the current width is larger than the max
    if(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        $(elem).css("width", maxWidth); // Set new width
        $(elem).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
        width = width * ratio;    // Reset width to match scaled image
    }

    // Check if current height is larger than max
    if(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        $(elem).css("height", maxHeight);   // Set new height
        $(elem).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }
    
}

function submitBookSearch() {
	var url = env.BOOK_SEARCH_AJAX + "?searchString=" + encodeURIComponent($("#searchString").val());
	replaceContainerAsync(url, "bookList");
}

function submitVideoSearch() {
	var url = env.VIDEO_SEARCH_AJAX + "?searchString=" + encodeURIComponent($("#searchString").val());
	replaceContainerAsync(url, "olderVideos");
}

function appendThumbnail(obj,width,heigth){
    var videoUrl = $(obj).attr('rev');
    if (videoUrl != null && videoUrl != '') {
	    var thUrl = $.jYoutube(videoUrl);
	    $(obj).html($(obj).html()+'<img height="'+heigth+'" width="'+width+'" src="'+thUrl+'" />');
    }
}

/* Youtube video */
var addYoutubeVideo = {
        init: function() {
             if ($(".youtube-video").length) {
                  $(".youtube-video").each(function(){
                       if(typeof $(this).attr("title") != "undefined" && typeof $(this).attr("title") != "undefined" ) {
                            vid =$(this).attr("title");
                            url=$(this).attr("rev");
                            isHttps = url.match("https://");
                            req = ( isHttps === null ) ? "http://" : "https://";
                            var $video = $("<iframe>")
                                 .attr({
                                      width: 400,
                                      height: 300,
                                      frameborder: 0,
                                      src: req + "www.youtube.com/embed/" + vid
                                 });
                            $video.appendTo($(this));
                            $(this).attr("title", "");
                            $(this).attr("class","vimeo-video"); //use vimeo CSS
                       } else {
                            $(this).remove();
                       }
                  });
             }
        }
};


function datepickPrevMonth(){
    var date = new Date();
    $("input.date-range").datepick('setDate',new Date(date.getFullYear(), date.getMonth()-1, 1),new Date(date.getFullYear(), date.getMonth(), 0));
}

function datepickThisMonth(){
    var date = new Date();
    $("input.date-range").datepick('setDate',new Date(date.getFullYear(), date.getMonth(), 1), new Date(date.getFullYear(), date.getMonth()+1, 0));
}

function datepickPrevWeek(){
    $("input.date-range").datepick('setDate',getPreviousWeekMonday(),getPreviousWeekSunday());
}

function datepickThisWeek(){
    $("input.date-range").datepick('setDate',getCurrentWeekMonday(),getCurrentWeekSunday());
}

function getCurrentWeekSunday() {
    var d = new Date();
    if (d.getDay() == 0) { // sunday
        return d;
    }
    else return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() + 7);
}

function getCurrentWeekMonday() {
    var d = new Date();
    if(d.getDay() == 0) { // sunday
        return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 6);
    }
    return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() + 1);
}

function getPreviousWeekSunday() {
    var d = new Date();
    if (d.getDay() == 0) { // sunday
        return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 7);
    }

    return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay());
}

function getPreviousWeekMonday() {
    var d = new Date();
    if(d.getDay() == 0) // sunday
        return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 13);
    return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 6);
}

function datepickToday(){
    $("input.date-range").datepick('setDate', 0);
}

function datepickYesterday(){
    $("input.date-range").datepick('setDate',-1);
}


function initBannerPopups(){
    $(".popup-banner").each(function(){
            width = $(this).attr("rev").split(",")[0]
            height = $(this).attr("rev").split(",")[1]
        
            var bannerProfiles = {
                    popup: {
                         width:   width,
                         height:  height,
                         center:    1,
                         createnew: 1,
                         resizable: 0,
                         scrollbars: 1
                    }
               }; 
            $(this).popupwindow(bannerProfiles);
    });
}

$(function(){
    addYoutubeVideo.init();
    
    
    var powertraderProfile = {
            popup: {
                 width:   typeof isUserAuthenticated != 'undefined' && isUserAuthenticated == "true" ? 786 : 1000,
                 height:  540,
                 center:    1,
                 createnew: 1,
                 resizable: 0,
                 scrollbars: 1
            }
       };
    
    var profiles = {
            popup: {
                 width:   640,
                 height:  510,
                 center:    1,
                 createnew: 0,
                 resizable: 0,
                 scrollbars: 1
            }
       };
       
    if($(".popup-window").length){
        $(".popup-window").popupwindow(profiles);
    }
    
    if($(".popup-powertrader").length){
        $(".popup-powertrader").popupwindow(powertraderProfile);
    }
    
    if($("input.date-range").length){
        $("input.date-range").datepick('destroy');
        $.datepick.setDefaults($.datepick.regional[env.SITE_LANGUAGE]);
         $("input.date-range").datepick({
              rangeSelect: true,
              monthsToShow: 2,
              rangeSeparator: " - ",
              onShow: function(picker, inst) {
                   picker.append('<table class="datepick-shortcuts"><tr><td class="first"><a href="#" onclick="datepickToday();">'+env.TODAY+'</a></td><td><a href="#" onclick="datepickYesterday();">'+env.YESTERDAY+'</a></td><td><a href="#"  onclick="datepickThisWeek();">'+env.THIS_WEEK+'</a></td><td><a href="#" onclick="datepickPrevWeek();">'+env.PREV_WEEK+'</a></td><td><a href="#" onclick="datepickThisMonth();">'+env.THIS_MONTH+'</a></td><td class="last"><a href="#" onclick="datepickPrevMonth();">'+env.PREV_MONTH+'</a></td></tr></table>');
             }
         });
    }
    
    if($("input.date").length){
        var settings = $.datepick.regional[env.SITE_LANGUAGE];
        settings.dateFormat = 'dd.mm.yyyy';
        $.datepick.setDefaults(settings);
         $("input.date").datepick();
    }

    if($(".popup-radio").length){
        var profiles = {
                popup: {
                     width:   240,
                     height:  130,
                     center:    1,
                     createnew: 1,
                     resizable: 0,
                     scrollbars: 0
                }
           };
        
        $(".popup-radio").popupwindow(profiles);
    }
});

$(document).ready(function() {
    $.ajaxSetup ({
        cache: false
    });
    initBannerPopups();
});