/*
 * @copyright Copyright 2005-2010, www.heroesworld.ru
 * @remark This script works only with jquery library www.jquery.com
 * @version 1.4.1
*/

/*
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="95" height="95" id="hw_generate_ws_indicator_image" align="right"> <param name="movie" value="frame.swf"> <param name="quality" value="high"><param name="wmode" value="transparent"><param name="menu" value="false"><param name="FlashVars" value="mode=screens"> <embed src="frame.swf" quality="high" wmode="transparent" menu="0" FlashVars="mode=screens"pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="95" height="95"></embed></object>
*/

postid_wsc_indicator_clicked = new Array();
popup_show_status = new Array();

function hw_debug(func,line,postid,msg)
{
    alert( "DEBUG ERROR: function " + func + ", on line " + line + ", postid = " + postid + ", message = " + msg );
}

function hw_convert_ws_to_score(ws)
{
	if( ws == "p" )
	{
		return 1;
	}
	if( ws == "n" )
	{
		return -1;
	}
	return 0;
}

function hw_get_ws_score(postid)
{
	if( wscArray != undefined )
	{
		if( wscArray[postid] != undefined )
		{
			var total_score = 0;

			for( i in wscArray[postid] )
			{
				var cur_ws = wscArray[postid][i].split("|",1);
				var total_score = total_score + hw_convert_ws_to_score(cur_ws[0]);
			}
			return total_score;
		}
        else
        {
            hw_debug("hw_get_ws_score",43,postid,"wscArray[postid] = undefined");
        }
	} else
    {
        hw_debug("hw_get_ws_score",47,postid,"wscArray = undefined");
    }
	return "error";
}

function hw_change_ws_src( flashObjectID, movieValue )
{
   var movie = $("#"+flashObjectID).attr("outerHTML");
   var alternative = 0;

   if( movie == undefined )
   {
       movie = document.getElementById( flashObjectID ).outerHTML;
       alternative = 1;
   }

   if( movie == undefined )
   {
       movie = document.getElementById( flashObjectID ).innerHTML;
       alternative = 2;
   }

   var re = /frame.swf/gim;
   movie = "" + movie;
   movie = movie.replace( re, movieValue+".swf" );

   if( alternative == 1)
   {
        document.getElementById( flashObjectID ).outerHTML = movie;
   }
   else if( alternative == 2 )
   {
        document.getElementById( flashObjectID ).innerHTML = movie;
   }
   else
   {
       $("#"+flashObjectID).attr("outerHTML", movie);
   }
}

function hw_generate_ws_indicator_image(postid)
{
	var ws_score = hw_get_ws_score(postid);

	if( ws_score != "error" )
	{
		var type = "n3";

		if( ws_score > 15 )
		{
		  type = "p3";
		} else if( ws_score > 7 )
		{
		  type = "p2";
		} else if( ws_score > 0 )
		{
		  type = "p1";
		} else if( ws_score == 0 )
		{
		  type = "p0";
		} else if( ws_score > -7 )
		{
		  type = "n1";
		} else if( ws_score > -15 )
		{
		  type = "n2";
		}

		hw_change_ws_src( "ws_indicator_"+postid, type );
		$('#ws_indicator_embed_'+postid).attr("src","http://www.heroesworld.ru/forum/images/ws_indicator/"+type+".swf");
	} else
    {
        hw_debug("hw_generate_ws_indicator_image",83,postid,"ws_score = error");
    }
}

function hw_generate_user_member_link(user_id,user_name)
{
	var html = "<a href=\"member.php?u="+user_id+"\">"+user_name+"</a>";
	return html;
}

function hw_generate_ws_popup_html(postid)
{
	var html = "<div id=\"wsc_popup_"+postid+"\" style=\"display:none;\">" +
"<div class=\"smallfont\" style=\"padding:10px;background-color:#EFEFEF;border:1px solid #0B198C; width:350px;\">" +
"<p><strong>Изменения боевого духа за это сообщение:</strong></p>";

if( wscArray != undefined )
{
	if( wscArray[postid] != undefined )
	{
		var total_score = 0;

		for( i in wscArray[postid] )
		{
			var cur_ws = wscArray[postid][i].split("|");
			var ws_sign = cur_ws[0];
			var total_score = total_score + hw_convert_ws_to_score(ws_sign);
			var user_id = cur_ws[1];
			var user_name = cur_ws[2];
			var user_comment = cur_ws[3];
			html = html + "<img src=\"http://www.heroesworld.ru/forum/images/reputation/"+ws_sign+"1.gif\" width=\"24\"> "+hw_generate_user_member_link(user_id,user_name)+", "+user_comment+"<br/>";
		}
	}
    else
    {
        hw_debug("hw_generate_ws_popup_html",118,postid,"wscArray[postid] = undefined");
    }
}
else
{
    hw_debug("hw_generate_ws_popup_html",123,postid,"wscArray = undefined");
}



var total_score_sign = "";
if( total_score_sign < 0 ) total_score_sign = "-";
if( total_score_sign > 0 ) total_score_sign = "-";

html = html +
"<hr>" +
"Суммарное изменение боевого духа за это сообщние: " + total_score_sign + total_score
	"</div>";

	return html;
}

function hw_generate_ws_indicator_popup(postid)
{
    if( postid_wsc_indicator_clicked != undefined )
	{
		postid_wsc_indicator_clicked[postid] = false;

		popup_id = "#wsc_popup_"+postid;
		indicator_id = "#ws_indicator_"+postid;

		var popup_html = hw_generate_ws_popup_html(postid);

		$(indicator_id).after(popup_html);

		eval( "$(indicator_id).mousedown( function(e)"+
	        "{"+
	        "    if( postid_wsc_indicator_clicked["+postid+"] )"+
	        "    {"+
	        "        $(\""+popup_id+"\").fadeOut(\"slow\");"+
	        "    } else"+
	        "    {"+
	        "        $(\""+popup_id+"\").fadeIn(\"slow\");"+
	        "        $(\""+popup_id+"\").css(\"position\", \"absolute\");"+
	        "        $(\""+popup_id+"\").css(\"left\",e.pageX - (e.pageX*0.45));"+
	        "        $(\""+popup_id+"\").css(\"top\",e.pageY + 10);"+
	        "    }"+
	        "    postid_wsc_indicator_clicked["+postid+"] = !postid_wsc_indicator_clicked["+postid+"];"+
	        "})" );

		eval( "$(indicator_id).mouseover( function(e)"+
		"{"+
		"	if( !postid_wsc_indicator_clicked["+postid+"] )"+
		"	{"+
		"        $(\""+popup_id+"\").fadeIn(\"slow\");"+
		"        $(\""+popup_id+"\").css(\"position\", \"absolute\");"+
		"        $(\""+popup_id+"\").css(\"left\",e.pageX - (e.pageX*0.30));"+
		"        $(\""+popup_id+"\").css(\"top\",e.pageY + 10);"+
		"	}"+
		"})");

		eval( "$(indicator_id).mouseout( function(e)"+
		"{"+
		"	if( !postid_wsc_indicator_clicked["+postid+"] )"+
		"	{"+
		"		$(\""+popup_id+"\").fadeOut(\"slow\");"+
		"   }"+
		"}) ");
	}
    else
    {
        hw_debug("hw_generate_ws_indicator_popup",192,postid,"postid_wsc_indicator_clicked = undefined");
    }
}

function hw_generate_popup_html(popup_id,popup_html, popup_width)
{
    var html = "<div id=\"hw_popup_"+popup_id+"\" style=\"display:none;\">" +
               "<div class=\"smallfont\" style=\"padding:10px;background-color:#EFEFEF;border:1px solid #0B198C; width:" + popup_width + "px;\">" + popup_html + "</div></div>";

    return html;
}

function hw_show_popup( event, popup_id, timer, popup_width )
{
    if( !popup_show_status[ popup_id ] )
    {
	    if( popup_width == false )
	    {
	       popup_width = 0;
	    }
		$("#hw_popup_"+popup_id).css( "position", "absolute" );
		$("#hw_popup_"+popup_id).css( "left", event.pageX + 10 - popup_width );
	    $("#hw_popup_"+popup_id).css( "top", event.pageY + 10 );
	    $("#hw_popup_"+popup_id).show();

	    popup_show_status[ popup_id ] = true;

	    if( timer != false )
	    {
	        setTimeout("hw_hide_popup( "+popup_id+" );", timer );
	    }
    }
}

function hw_hide_popup( popup_id )
{
    $("#hw_popup_"+popup_id).hide();
    popup_show_status[ popup_id ] = false;
}

function HwSignatureHelper() {
    var SMILEY_MAX_HEIGHT = 48;
    var SMILEY_MAX_WIDTH = 96;
    var SMALL_IMG_MAX_WIDTH = 350;
    var SMALL_IMG_MAX_HEIGHT = 20;
    var LARGE_IMG_MAX_WIDTH = 500;
    var LARGE_IMG_MAX_HEIGHT = 140;
    var VERY_LARGE_IMAGES_LIMIT = 0;
    var LARGE_IMAGES_LIMIT = 2;
    var SMALL_IMAGES_LIMIT = 5;

    /**
     * @param {String} expr An expression whose matched elements will be appended with warning
     */
    this.appendSignatureWarning = function(expr) {
        $(expr).after().append("<hr><p><h4 style='color:red;'>Размеры отдельных изображений используемых в подписи превышают установленный в <a href=\"http://forum.heroesworld.ru/faq.php?faq=hw_help#hw_help_rules_14\">правилах портала лимит</a>, либо превышен лимит количества изображений для подписи. Размер изображений был уменьшен автоматически (они отмечены красной рамкой). Пожалуйста, уменьшите размеры отдельных изображений или сократите их количество так, чтобы это не нарушало <a href=\"http://forum.heroesworld.ru/faq.php?faq=hw_help#hw_help_rules_14\">правил портала</a>.</h4></p>");
    }

    /**
     * @param {Array} smileyImages Array of smiles (jQuery elements)
     * @param {Array} smallImages Array of small images (jQuery elements)
     * @param {Array} largeImages Array of large images (jQuery elements)
     * @param {Array} veryLargeImages Array of very large images (jQuery elements)
     * @remark signature is invalid when large images more than two, small images more than five (if small images is five it equals one large image)
     * @returns bool
     */
    this.isSignatureValid = function(smileyImages, smallImages, largeImages, veryLargeImages) {
        if (veryLargeImages.length > VERY_LARGE_IMAGES_LIMIT) {
            return false;
        }

        if (smallImages.length > SMALL_IMAGES_LIMIT) {
            return false;
        }

        if (largeImages.length > LARGE_IMAGES_LIMIT) {
            return false;
        }

        return true;
    }

    /**
     * @param {Array} smileyImages Array of smiles (jQuery elements)
     * @param {Array} smallImages Array of small images (jQuery elements)
     * @param {Array} largeImages Array of large images (jQuery elements)
     * @param {Array} veryLargeImages Array of very large images (jQuery elements)
     * @remark
     */
    this.fixSignatureImages = function(smileyImages, smallImages, largeImages, veryLargeImages) {
        for (i = 0; i < veryLargeImages.length; i++) {
            $(veryLargeImages[i]).height(LARGE_IMG_MAX_HEIGHT)
            $(veryLargeImages[i]).css("border", "3px solid red");
        }
    }

    /**
     * @param {String} expr An expression whose matched elements will be checked
     * @remark 96x48 larges smiley
     * @returns bool
     */
    this.isImageSmiley = function(expr) {
        return ($(expr).width() <= SMILEY_MAX_WIDTH && $(expr).height() <= SMILEY_MAX_HEIGHT);
    }

    /**
     * @param {String} expr An expression whose matched elements will be checked
     * @remark 350x20 small image (like userbar)
     * @returns bool
     */
    this.isImageSmall = function(expr) {
        return (!this.isImageSmiley(expr) &&
                $(expr).width() <= SMALL_IMG_MAX_WIDTH && $(expr).height() <= SMALL_IMG_MAX_HEIGHT);
    }

    /**
     * @param {String} expr An expression whose matched elements will be checked
     * @remark 500x140 large image
     * @returns bool
     */
    this.isImageLarge = function(expr) {
        return (!this.isImageSmiley(expr) &&
                !this.isImageSmall(expr) &&
                $(expr).width() <= LARGE_IMG_MAX_WIDTH && $(expr).height() <= LARGE_IMG_MAX_HEIGHT);
    }

    this.processThreadSignatures = function() {
        var divs = $('div');
        var signatures = new Array();

        for( di = 0; di < divs.length; di++ ) {
            var div = $(divs[di]);

            if(div.attr('id') == "signature") {
                signatures.push(div);
            }
        }

        for( si = 0; si < signatures.length; si++ ) {
            this.processSignature(signatures[si]);
        }
    }

    this.processProfileSignature = function() {
        var elements = $('.alt1');

        for( i = 0; i < elements.length; i++ ) {
          var e = $(elements[i]);

          if( e.attr('title') == "Подпись" ) {
              this.processSignature(elements[i]);
          }
        }
    }

    this.processSignature = function(expr) {
        var signature = $(expr);

            var imgs = signature.find('img, * > img');

            var smileyImages = new Array();
            var smallImages = new Array();
            var largeImages = new Array();
            var veryLargeImages = new Array();

            for( ii = 0; ii < imgs.length; ii++ ) {
                if (this.isImageSmiley(imgs[ii])) {
                    smileyImages.push(imgs[ii]);
                } else if (this.isImageSmall(imgs[ii])) {
                    smallImages.push(imgs[ii]);
                } else if( this.isImageLarge(imgs[ii])) {
                    largeImages.push(imgs[ii]);
                } else {
                    veryLargeImages.push(imgs[ii]);
                }
            }

            if (!this.isSignatureValid(smileyImages, smallImages, largeImages, veryLargeImages)) {
                this.fixSignatureImages(smileyImages, smallImages, largeImages, veryLargeImages);
                this.appendSignatureWarning(signature);
            }
    }
}

function HwHelper() {    
    this.SignatureHelper = new HwSignatureHelper();
}

HW = new HwHelper();

window.HW = HW;
