// **********************************
// poemScript v2.00 free software
// الرجاء عدم إزالة وصف الحقوق
// Please don't remove the copyright note
// هذا الاسكريبت بواسطة علوي باعقيل
// this script (poem.js) written by Alawi Hussain Ba3qeel (software@rayaheen.net)
// for IE browser
// **********************************

////////////////////////// set default parameters //////////////////////////
function poem_setDefaultVar() {

  // إذا لم يوجد الخط الذي حدده المستخدم
  // فإن الاتش تي ام ال يختار تلقائيا واحد من الخطوط التالية علىالترتيب
  // فإن لم يجد الأول انتقل إلى الثاني وهكذا

  poemDefaultFont = "Arial";

  poemType = "0",
  poemAlign = "center",
  poemLine = "1";
  poemUse = "0";

  poemFontName = "",
  poemFontSize = "4",  // 1 to 7
  poemFontColor = "#00407D",
  poemFontBold = "bold",
  poemFontItalic = "normal";

  poemBackColor = "",
  poemBackImage = "none";

  poemSideImage = "none";

  poemBreakImage = "none";

  poemBorderStyle = "none",
  poemBorderWidth = "4",
  poemBorderColor = "gray";
  poemBorderShadow = "";
  poemWidth = "0";

  poemShadowColor = "";
  poemShadowGlowColor = "";
  poemGlowColor = "";
  poemStretch = "0";

  poemSerialNum = "0",
  poemSerialNumColor = "";
  poemSerialNumSize = "";

}

//////////////////////////////////////////////////////////////////////////
  var poemSpaceWidth, poemExtendWidth;
  var poemToolFix, poemPrevHTML;

  var poemLetters1 = "اأإآؤءدذرزوةى"
  var poemLetters2 = "اأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى";
  var poemLetters3 = "ًٌٍَُِّْ";

  function poemVal(n) {
	  n = Math.round(n);
	  if (isNaN(n)) n = 0;
	  return n;
  }

  function create_poemTestWidth_table() {
    if (!document.getElementById("poemtestWidth")) {
      var HTML = '<table border="0" width="1pt" style="visibility:hidden;position:absolute">';
      HTML += "<tr><td id='poemTestWidth' width=0 nowrap></td></tr>";
      HTML += "</table>";
      document.body.insertAdjacentHTML("afterBegin", HTML);
    }
  }

  function poem_getValue(t, p) {
    var r = new RegExp("([ \"]|^)" + t + "[ ]*=[ ]*\"[^\"]*\"", "i");
    var m = p.match(r);
    if (!m) {
      r = new RegExp("([ \"]|^)" + t + "[ ]*=[ ]*[^\" ]*([ ]|$)", "i");
      m = p.match(r);
      if (!m)
        return "";
    }
    m = m[0];
    m = m.replace(/\"/gi,"");
    var i = m.search("=");
    return m.substring(i + 1);
  }

  function poem_getDefault(p, d) {
	  var r = ((p)?p:d);
	  return poem_trim(r);
  }

  function poem_setArg(arg) {
    var par, poemFontSize2;

    par = poem_getValue("font", arg) + ",,,,";  //comas = number of arrays - 1
    par = par.split(",");
    poemFontName = poem_getDefault(par[0], poemFontName);
	poemFontName = poemFontName.replace(/\-/g, ",");
    poemFontSize2 = poemVal(poem_getDefault(par[1], poemFontSize));
	if (poemFontSize2 < 1 || poemFontSize2 > 7)
		poemFontSize2 = poemFontSize;
	poemFontSize = poemFontSize2;

    poemFontColor = poem_getDefault(par[2], poemFontColor);
    poemFontBold = poem_getDefault(par[3], poemFontBold);
    poemFontItalic = poem_getDefault(par[4], poemFontItalic);

    par = poem_getValue("border", arg) + ",,";
    par = par.split(",");
    poemBorderStyle = poem_getDefault(par[0], poemBorderStyle);
    poemBorderWidth = poemVal(poem_getDefault(par[1], poemBorderWidth));
    poemBorderColor = poem_getDefault(par[2], poemBorderColor);
	poemBorderShadow = poem_getDefault(par[3], poemBorderShadow);

    par = poem_getValue("num", arg) + ",,";
	par = par.split(",");
    poemSerialNum = poemVal(poem_getDefault(par[0], poemSerialNum));
	poemSerialNumColor = poem_getDefault(par[1], poemSerialNumColor);
    poemSerialNumSize = poem_getDefault(par[2], poemSerialNumSize);

    par = poem_getValue("type", arg);
    poemType = poemVal(poem_getDefault(par, poemType));

    par = poem_getValue("align", arg);
    poemAlign = poem_getDefault(par, poemAlign).toLowerCase();

    par = poem_getValue("line", arg);
    poemLine = poemVal(poem_getDefault(par, poemLine));
	if (poemLine == 0)
		poemLine = "padding-bottom:0pt";
	else
		poemLine = "padding-bottom:5pt";

	par = poem_getValue("break", arg);
    poemBreakImage = poem_getDefault(par, poemBreakImage);
	if (poemBreakImage == "none" || poemBreakImage == "")
		poemBreakImage = "-";
	else
		poemBreakImage = '<img border="0" src="' + poemBreakImage + '">';

	par = poem_getValue("use", arg);
    poemUse = poemVal(poem_getDefault(par, poemUse).toLowerCase());

	par = poem_getValue("shcolor", arg);
    poemShadowColor = poem_getDefault(par, poemShadowColor);

    par = poem_getValue("shgcolor", arg);
    poemShadowGlowColor = poem_getDefault(par, poemShadowGlowColor);

    par = poem_getValue("gwcolor", arg);
    poemGlowColor = poem_getDefault(par, poemGlowColor);

	par = poem_getValue("bkcolor", arg);
    poemBackColor = poem_getDefault(par, poemBackColor);

    par = poem_getValue("bkimage", arg);
    poemBackImage = poem_getDefault(par, poemBackImage);

    par = poem_getValue("sdimage", arg);
    poemSideImage = poem_getDefault(par, poemSideImage);

    par = poem_getValue("stretch", arg);
    poemStretch = poemVal(poem_getDefault(par, poemStretch));
	poemStretch = Math.round(poemStretch * 0.75);

    par = poem_getValue("pwidth", arg);
    poemWidth = poemVal(poem_getDefault(par, poemWidth));
	poemWidth = Math.round(poemWidth * 0.75);

    //////////// set style ///////////
    var facesize = new Array("xx-small","x-small","small","medium","large","x-large","xx-large");
    poemFontSize = facesize[poemFontSize - 1];

    poemFontName += "," + poemDefaultFont;

    poemTestWidth.style.fontFamily = poemFontName;
    poemTestWidth.style.fontSize = poemFontSize;
    poemTestWidth.style.fontWeight = poemFontBold;
    poemTestWidth.style.fontStyle = poemFontItalic;

    ///////////////////////////////////
  }

  function poem_trim(t) {
    t = t.replace(/^[ ]+/, "");
    t = t.replace(/[ ]+$/, "");
    return t;
  }

  function poem_textWidth(t) {
	t = t.replace(/ /g, "&nbsp;");
	t = t.replace(/\|lt\|/g, "<");
	t = t.replace(/\|eq\|/g, "=");
	t = t.replace(/\|sp\|/g, " ");
	t = t.replace(/\^/g, "");
	poemTestWidth.innerHTML= t;
    return (poemTestWidth.clientWidth - 2) * 0.75;
  }

  function poem_strReplace(t, s1, s2, c) {
	if (c <= 0)
	  return;
    t=t.split(s1);
    var s="";
    for (var i=t.length-1;i>0;i--)
	  if (c-->0)
        s = s2 + t[i] + s;
	  else
		s = s1 + t[i] + s;

	s = t[0] + s;
    return s;
  }

  function poem_count(str, ch) {
    var c = 0;
    for (var i = 0; i < str.length; i++)
      c += (str.charAt(i) == ch);
    return c;
  }

  function poem_space(n) {
    if (n == 1)
      return " ";
    return  " " + poem_space(n-1);
  }

  function poem_createExtend(t) {
    var alef = "اأإآ";
    var s = "";
    var befor = "", ch = "";
    t = t.replace(/الله/g,"alh");
	t = t.replace(/لله/g,"lah");
    for (i = 0; i < t.length; i++) {
      ch = t.charAt(i);
      if (poemLetters2.indexOf(ch.charAt(0)) != -1 || ch.charAt(0) == "ء") {
        if (befor != "")
          if (poemLetters1.indexOf(befor.charAt(0)) == -1 && poemLetters2.indexOf(ch.charAt(0)) != -1
            && (befor.charAt(0) != "ل"
            || alef.indexOf(ch.charAt(0)) == -1))
            s += "^";
        befor = ch;
        s += ch;
      }
      else {
        s += ch;
        if (poemLetters3.indexOf(ch.charAt(0)) == -1)
          befor = "";
      }
    }
    s = s.replace(/alh/g,"الله");
	s = s.replace(/lah/g,"لله");
    return s;
  }

  function poem_extend(n) {
	if (n <= 0)
      return "";
    if (n == 1)
      return "ـ";
    return  "ـ" + poem_extend(n-1);
  }

  function poem_justifyBYextend(t, w) {
    var ex = 0, i, d, n, p, m;
    ex = poem_count(t, "^");
    if (ex == 0) return t;
    d = Math.floor((w - poem_textWidth(t.replace(/\^/g,""))) / poemExtendWidth);
    t = t.split(" ");
    n = 0;
    for (i = 0; i < t.length; i++)
      n += (t[i].indexOf("^") != -1);
    p = Math.floor(d / n);
    m = d % n;
    for (i = t.length-1; i >= 0; i--) {
      ex = poem_count(t[i], "^");
      if (ex == 0)
        continue;
      d = p + (m-- > 0);
      n = Math.floor(d / ex);
      if (n > 0)
        t[i] = t[i].replace(/\^/g, "^" + poem_extend(n));
      if (d % ex > 0)
        t[i] = poem_strReplace(t[i], "^", "ـ", d % ex);
    }
    t = t.join(" ");
    t = t.replace(/\^/g, "");
    return t;
  }

  function poem_justifyBYspace(t, w, dir) {
    var sp = 0, i, d, tw, n;
    sp = poem_count(t, " ");
    if (sp != 0) {
      d = Math.floor((w - poem_textWidth(t)) / poemSpaceWidth);
      n = Math.floor(d / sp);
      if (n > 0)
        t = t.replace(/ /g, poem_space(n + 1));
      if (d % sp > 0)
        t = poem_strReplace(t, poem_space(n + 1), poem_space(n + 2), d % sp);
    }
    tw = w - poem_textWidth(t);
    if (tw > 0) {
      i = t.lastIndexOf(" ");
      if (i == -1)
        if (dir == 0)
          return t;
        else
          i = ((dir==2)?-1:t.length-1);
    } else
		tw = 0;
	t = t.substr(0, i+1) + poemToolFix.replace(/%w%/,tw+"pt ") + t.substr(i+1);
    return t;
  }

  function poem_justify(t, w, dir) {
    if (poemUse == 0) t = poem_justifyBYextend(t, w);
    return poem_justifyBYspace(t, w, dir);
  }

  function showPoemLine(preview, html) {
	if (preview)
		poemPrevHTML += html;
	else
		document.write(html);
  }

  function doPoem(preview) {
	var found = 0, pre, poem;
	poem_setDefaultVar();

	if (preview == 1) {
		pre = poemOBJECT;
		pre.style.display = "none";
		poemPrevHTML = "";
		poem = pre.value;
	}
	else if (preview == 2) {
		pre = poemOBJECT;
		poemPrevHTML = "";
		poem = pre.value;
	}
	else {
		var d = document.getElementsByTagName("pre");
		pre = d[d.length -1];
		pre.style.display = "none";
		poem = pre.innerHTML;
	}	
	poem = poem.replace(/<br>/gi, "");
	poem = poem.replace(/^[\r]*/g, "");
	poem = poem.replace(/[\r]*$/g, "");
	if (!pre.tag)
		pre.tag = "";
	if (!preview)
		pre.innerHTML = "";
	var arg = pre.tag.replace(/\\\"/g, "'");

	create_poemTestWidth_table();

	poem_setArg(arg);

	poemToolFix = "<span style='font-size:1pt;width:%w%;'></span>";
    poemToolFix = poemToolFix.replace(/ /g,"^");

	poem = poem.replace(/[\^\f\n\t\v]/g, "");
    poem = poem.replace(/[ ]+/g, " ");
	poem = poem.replace(/^[ ]/g, "");
	poem = poem.replace(/[ ]$/g, "");
	poem = poem.replace(/[ ]=/g, "=");
	poem = poem.replace(/=[ ]/g, "=");
	poem = poem.replace(/[ ]\r/g, "\r");
	poem = poem.replace(/\r[ ]/g, "\r");
	poem = poem.replace(/=ـ/g, "=ext1");
	poem = poem.replace(/ـ=/g, "ext2=");
	poem = poem.replace(/ـ/g, "");
	poem = poem.replace(/ext1/g, "ـ");
	poem = poem.replace(/ext2/g, "ـ");
	poem = poem.replace(/</g, "&lt;");
	poem = poem.replace(/>/g, "&gt;");
    poem = poem.replace(/\|eq\|/g,"");
	poem = poem.replace(/\|sp\|/g,"");
	poem = poem.replace(/\|lt\|/g,"");

	poem = poem.replace(/\[c[ ]+#{0,1}([a-zA-Z0-9]+)\]([^=]*)\[\/c\]/gi, '<font color="$1">$2</font>');
	poem = poem.replace(/\[s[ ]+([1-7])\]([^=]*)\[\/s\]/gi, '<font size="$1">$2</font>');
	poem = poem.replace(/\[b\]([^=]*)\[\/b\]/gi, '<b>$1</b>');
	poem = poem.replace(/\[i\]([^=]*)\[\/i\]/gi, '<i>$1</i>');
	poem = poem.replace(/\[u\]([^=]*)\[\/u\]/gi, '<u>$1</u>');
	poem = poem.replace(/\[sp[ ]+#{0,1}([a-zA-Z0-9]+)\]([^=]*)\[\/sp\]/gi, '<sup style="font-size:75%;color:$1">$2</sup>');
	poem = poem.replace(/\[sb[ ]+#{0,1}([a-zA-Z0-9]+)\]([^=]*)\[\/sb\]/gi, '<sub style="font-size:75%;color:$1">$2</sub>');
	poem = poem.replace(/\[sp\]([^=]*)\[\/sp\]/gi, '<sup style="font-size:75%">$1</sup>');
	poem = poem.replace(/\[sb\]([^=]*)\[\/sb\]/gi, '<sub style="font-size:75%">$1</sub>');

	var ti, tj, tag;
	var re = /<[^<>\r]*>/;
	while (1) {
		ti = poem.search(re);
		if (ti == -1) break;
		if (ti > -1) {
			tj = poem.indexOf(">", ti);
			tag = poem.substring(ti, tj + 1);
			tag = tag.replace(/</g, "|lt|");
			tag = tag.replace(/=/g, "|eq|");
			tag = tag.replace(/ /g, "|sp|");
			poem = poem.replace(re, tag);
		}
	}
	poem = poem.replace(/\|lt\|br\|sp\|\/>/gi, "");
	poem = poem.replace(/\|lt\|br>/gi, "");

	poemExtendWidth = poem_textWidth("ش" + "ــ" + "ش");
    poemExtendWidth -= poem_textWidth("ش" + "ـ" + "ش");
    poemSpaceWidth = poem_textWidth("ش" + "&nbsp;&nbsp;" + "ش");
    poemSpaceWidth -= poem_textWidth("ش" + "&nbsp;" + "ش");

	var tmp, MTW, MW = 0;

	tmp = "\r" + poem + "\r";
	tmp = tmp.replace(/=/g, "<br>");
	tmp = tmp.replace(/\r/g, "<br>");
	var MTW = poem_textWidth(tmp);
	tmp = "";

	if (poemType == 0)
		MW = Math.floor((poemStretch * 3) / 7);
	else if (poemType == 1)
		MW = Math.floor((poemStretch - 10) / 2);
	else if (poemType == 2)
		MW = Math.floor(poemStretch / 1.5);
	else if (poemType == 3)
		MW = poemStretch;

	if (MW > MTW) MTW = MW;

	if (poemUse == 0)
  	   poem = poem_createExtend(poem);


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

    var poemBodyStyle = "", fonts = "", filters = "";
	fonts += ";font-family:" + poemFontName;
    fonts += ";font-size:" + poemFontSize;
    fonts += ";color:" + poemFontColor;
    fonts += ";font-weight:" + poemFontBold;
    fonts += ";font-style:" + poemFontItalic;
    poemBodyStyle += ";background-color:" + poemBackColor;
	if (poemBackImage != "none" && poemBackImage != "")
		poemBodyStyle  += ";background-position:top right;";
	poemBodyStyle += ";border:" + poemBorderWidth + " " + poemBorderStyle + " " + poemBorderColor;
	poemBodyStyle += ";width:" + poemWidth + "pt";

	if (poemShadowColor != "")
		filters += " dropshadow(color=" + poemShadowColor + ")";
	if (poemShadowGlowColor != "")
		filters += " shadow(direction=135,color=" + poemShadowGlowColor + ")";
	if (poemGlowColor != "")
		filters += " glow(color=" + poemGlowColor + ")";

	showPoemLine(preview, '<div dir="rtl" align="' + poemAlign + '">');

	if (poemBorderShadow != "") {
		showPoemLine(preview, '<table border=0 width=1px cellpadding=0 cellspacing=0 style="border-collapse: collapse" bordercolor=#111111><tr>');
		showPoemLine(preview, '<td height=100% style="padding-top:10px"><div style="height:100%;width:5px;background-color:' + poemBorderShadow + ';font-size:1pt"></div></td>');
		showPoemLine(preview, '<td width=1px valign=top>');
	}
    showPoemLine(preview, '<table background="' + poemBackImage + '" border=0 cellpadding=0 cellspacing=0 style="' + poemBodyStyle + '"><tr>');
	if (poemSideImage != "none" && poemSideImage != "") {
		showPoemLine(preview, '<td width=1pt background="' + poemSideImage + '" style="background-repeat:repeat-y">');
		showPoemLine(preview, '<img border=0 src="' + poemSideImage + '" style="visibility:hidden"></td>');
	}
	showPoemLine(preview, '<td align=center style="padding:5pt" valign=top>');
	showPoemLine(preview, '<table border=0 cellpadding=0 cellspacing=0 width=1px style="' + fonts + '; filter:' + filters + '">');

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

	poem = poem + "\r";

	var L, R, i, j = 0, cr = 0, sn = 0, sep;
	var poemSide, poemSideNum, wnum;
	if (poemSerialNum > 0)
		sn = poemSerialNum - 1;
    while (1) {
   	  poemSideNum = "";
      poemSide = "";
	  sep = false;
      cr = poem.indexOf("\r", cr);
	  if (cr == -1) break;
      if (poem.substring(j, cr) != "") {
        i = poem.indexOf("=", j);
        if (i == -1 || i > cr) i = cr; //no '=' in this line
        L = poem.substring(j, i);
		if (L == "-") {
			sep = true;
			L = poemBreakImage;
		} else if (L != "\r" && L != "") {
			if (i != cr)
				L = poem_justify(L, MTW, 1);
			else {
				L = poem_justify(L, MTW, 0);
			}
			L = L.replace(/ /g, "&nbsp;");
			L = L.replace(/\^/g, " ");
		}

		R = poem.substring(i + 1, cr);
		if (R == "-") {
			sep = true;
			R = poemBreakImage;
		} else if (R != "\r" && R != "") {
			R = poem_justify(R, MTW, 2);
			R = R.replace(/ /g, "&nbsp;");
			R = R.replace(/\^/g, " ");
		}

		if (poemType == 0) {
		  if (i != cr) {
			    if (L == "") L = poemToolFix.replace(/%w%/, MTW + "pt").replace(/\^/, " ");
				if (R == "") R = poemToolFix.replace(/%w%/, MTW + "pt").replace(/\^/, " ");
				poemSide = L + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + R;
				//poemSide = L + poemToolFix.replace(/%w%/, Math.floor(MTW / 3) + "pt").replace(/\^/, " ") + R;
		  } else
			    poemSide = L;
		  poemSide = '<div align=center style="' + poemLine + '">' + poemSide + '</div>';
		  poemSideNum = ((sep) ? " " : ++sn);
		}
		else if (poemType == 1) {
			if (i == cr) {
				poemSide = '<div align=center style="' + poemLine + '">' + L + '</div>';
			} else {
				poemSide = '<div align=right style="width:' + (2 * MTW + 10) + 'pt;' + poemLine + '">' + L + '</div>';
				poemSide += '<div align=left style="width:' + (2 * MTW + 10) + 'pt;' + poemLine + '">' + R + '</div>';
			}
			poemSideNum = ((sep) ? " " : ++sn);
		}
		else if (poemType == 2) {
			if (i == cr) {
				poemSide = '<div align=center style="' + poemLine + '">' + L + '</div>';
			} else {
				poemSide = '<div align=right style="width:' + Math.floor(MTW * 1.4) + 'pt;' + poemLine + '">' + L + '</div>';
				poemSide += '<div align=left style="width:' + Math.floor(MTW * 1.4) + 'pt;' + poemLine + '">' + R + '</div>';
			}
			poemSideNum = ((sep) ? " " : ++sn);
		}
		else if (poemType == 3) {
		  poemSideNum = ((sep) ? " " : ++sn);
		  if (L == "") L = "&nbsp;";
		  if (R == "") R = "&nbsp;";
		  poemSide = '<div style="' + poemLine + '">' + L + '</div>';
  		  poemSide += '<div style="' + poemLine + '">' + R + '</div>';
		}
	  } else
		  poemSide += '&nbsp;';

	  poemSide = poemSide.replace(/\|eq\|/g,"=");
	  poemSide = poemSide.replace(/\|sp\|/g," ");
	  poemSide = poemSide.replace(/\|lt\|/g,"<");

	  if (poemSerialNum > 0 && poemSideNum != "")
		  showPoemLine(preview, '<tr><td align=left valign=top style="color:' + poemSerialNumColor + ';font-size:' + poemSerialNumSize + ';' + poemLine + '" nowrap>&nbsp;' + poemSideNum + poemToolFix.replace(/%w%/, Math.floor(MTW / 15) + "pt").replace(/\^/, " ") + '</td>');
	  showPoemLine(preview, '<td align=center valign=top nowrap style="padding-right:8pt;padding-left:4pt">' + poemSide + '</td></tr>');

	  cr += 1;
	  j = cr;
    }

    showPoemLine(preview, "</table></td></tr></table>");
	if (poemBorderShadow != "") {
	    showPoemLine(preview, '</td></tr><tr>');
  		showPoemLine(preview, '<td rowspan=3 colspan=2 width=100% style="padding-left:10px"><div style="width:100%;height:5px;background-color:' + poemBorderShadow + ';font-size:1pt"></div></td></tr></table>');
	}
	showPoemLine(preview, "</div>");

	if (preview)
		poemPreview.innerHTML = poemPrevHTML;
	poemPrevHTML = "";

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

	poem_textWidth("");
  }
