﻿// JavaScript to support mithras.org
// mithrasorg.js - release 005
//
// Original material (c) Mithras.org 2003
//
// Helped along the way, thanks to:
//   Weblog engine:       Movabletype.org
//   Farsi text handler:  Farsitools (Sourceforge) / Persianblog 
//   Calendar functions:  John Walker, http://www.fourmilab.ch/ 
//   Expandable sections: M.C. Matti, http://www.webreference.com/programming/css_content/index.html
//   Cookie functions:    Tomer Shiran, copyright (c) 1996-1997 Athenia Associates, http://www.webreference.com/js/


// Email and web page icon routines

function iconemail(sTxt) {
	if (sTxt != "") {
		document.write('<a href="mailto:' + sTxt + '"><img src="/images/envelope.gif"  border="0"></a>&nbsp;');
	}
}

function iconwebpage(sTxt) {
	sOutput = "";
	if (sTxt != "") {
		sOutput += '<a href="javascript:pop_under(\'';
		sOutput += sTxt;
		sOutput += '\');"><img src="/images/house.gif" border="0"></a>&nbsp;';
	}
	document.write ( sOutput );
}

function iconauthor(sAuthor, sURL) {
	sOutput = "";
	if (sAuthor != "") {
		sOutput += 'نويسنده:&nbsp;';
		if (sURL != "") {
			sOutput += '<a target="_blank" href="' + sURL + '">' + sAuthor + '</a>';
		} else {
			sOutput += sAuthor;
		}
		sOutput += '&nbsp;&nbsp;&nbsp;'
	}
	document.write ( sOutput );

}

function scrambler(sTxt) {
	var sOutput = "";

	for (i = 0 ; i < sTxt.length ; i++) {
		switch (sTxt.charAt(i)) {
			case '.' :
				sOutput += ' نقطه ';
				break;
			case '@' :
				sOutput += ' در ';
				break;
			default :
				sOutput += sTxt.charAt(i);
		}
	}
	alert ('Input was: '+sTxt+', output is: '+sOutput);
	return sOutput;
}


var PERSIAN_DAYS = new Array(
	"شنبه","يکشنبه","دوشنبه","سه شنبه","چهار شنبه","پنجشنبه","جمعه");

var PERSIAN_DIGITS = new Array(
	"۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹");

var PERSIAN_MONTHS = new Array(
	"فروردين","ارديبهشت","خرداد","تير","مرداد","شهريور","مهر","آبان","آذر","دی","بهمن","اسفند");

var BUTTON_LANG = new Array(
	"انگليسی",
	"فارسی");

var BUTTON_KEYB = new Array(
	"منطقی",
	"ايرانی");


var langFarsi;		
var keybFarsi;		


function farsinum(sTxt) {
	var sOutput = "";

	for (i = 0 ; i < sTxt.length ; i++) {
		if (sTxt.charCodeAt(i) >= 48 && sTxt.charCodeAt(i) <= 57)
			sOutput += PERSIAN_DIGITS[sTxt.charCodeAt(i) - 48];
	}
	
	return sOutput;
}

function farsidate(sInput)
{

	var dd, mm, yy, gd, nFirstcomma, nSecondcomma;
	var sDelimiter = "/";

	nFirstcomma = sInput.indexOf(sDelimiter, 1);
	nSecondcomma = sInput.indexOf(sDelimiter, nFirstcomma + 1);
	
// Even though mithras.org uses dd/mm/yy throughout, as a concession to our American friends we'll default to "Great Satan" format

// Strip off leading zeroes from the parsed date components - this squiffs the function
	mm = sInput.substring(0, nFirstcomma);
	dd = sInput.substring(nFirstcomma + 1, nSecondcomma);
	yy = sInput.substring(nSecondcomma + 1);

	if (mm.charAt(0) == "0") {mm = mm.charAt(1)};
	if (dd.charAt(0) == "0") {dd = dd.charAt(1)};
//	No need to process yy - this is passed as a four digit year

	gd = gregorian_to_jd(parseInt(yy), parseInt(mm), parseInt(dd));

	return jd_to_persian(gd);

}

// Pop-under routine - to open comment author's web pages underneath

function pop_under(url) {
	wintmp=window.open(url);
//	wintmp.blur();
	window.focus();
}
// Expandable / Collapsable sections

function dsp(loc){
   if(document.getElementById){
      var foc=loc.firstChild;
      foc=loc.firstChild.innerHTML?
         loc.firstChild:
         loc.firstChild.nextSibling;
      foc.innerHTML=foc.innerHTML=='+'?'-':'+';
      foc=loc.parentNode.nextSibling.style?
         loc.parentNode.nextSibling:
         loc.parentNode.nextSibling.nextSibling;
      foc.style.display=foc.style.display=='block'?'none':'block';}
}  


// Multibrowser text handler

function farsitext (keyCode, key) {

var farsikey = [	// Farsi keyboard map based on ASCII characters 
	0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x066A, 0x0026, 0x0027, 
	0x0029, 0x0028, 0x002A, 0x002B, 0x060C, 0x002D, 0x002E, 0x002F, 
	0x06F0, 0x06F1, 0x06F2, 0x06F3, 0x06F4, 0x06F5, 0x06F6, 0x06F7, 
	0x06F8, 0x06F9, 0x003A, 0x061B, 0x003E, 0x003D, 0x003C, 0x061F, 
	0x0040, 0x0622, 0x200B, 0x0635, 0x064A, 0x0626, 0x0625, 0x0686, // Changed third char from 0629 (arabic heh) to zerowidth space
	0x062D, 0x0622, 0x0698, 0x062E, 0x0643, 0x064A, 0x0624, 0x0623, 
	0x0625, 0x063A, 0x064B, 0x0634, 0x0637, 0x0621, 0x0056, 0x064C, 
	0x0638, 0x0626, 0x0630, 0x005D, 0x005C, 0x005B, 0x005E, 0x005F, 
	0x0060, 0x0627, 0x0628, 0x062B, 0x062F, 0x0639, 0x0641, 0x06AF, 
	0x0647, 0x0626, 0x062C, 0x06A9, 0x0644, 0x0645, 0x0646, 0x200B,  // Changed last char from 062E to 200B - duped khe to zerowidth space
	0x067E, 0x0642, 0x0631, 0x0633, 0x062A, 0x0639, 0x0648, 0x0635, 
	0x0636, 0x06CC, 0x0632, 0x007D, 0x007C, 0x007B, 0x007E
];            

var irankey = [	// Farsi keyboard map based on ISIRI 2901
	0x0020, 0x0021, 0x061B, 0x066B, 0xFDFC, 0x066A, 0x060C, 0x06AF, 
	0x0029, 0x0028, 0x002A, 0x002B, 0x0648, 0x002D, 0x002E, 0x002F, 
	0x06F0, 0x06F1, 0x06F2, 0x06F3, 0x06F4, 0x06F5, 0x06F6, 0x06F7, 
	0x06F8, 0x06F9, 0x003A, 0x06A9, 0x003E, 0x003D, 0x003C, 0x061F, 
	0x066C, 0x0624, 0x200C, 0x0698, 0x064A, 0x064D, 0x0625, 0x0623, 
	0x0622, 0x0651, 0x0629, 0x00BB, 0x00AB, 0x0621, 0x004E, 0x005D, 
	0x005B, 0x0652, 0x064B, 0x0626, 0x064F, 0x064E, 0x0056, 0x064C, 
	0x0058, 0x0650, 0x0643, 0x062C, 0x067E, 0x0686, 0x00D7, 0x0640, // mod the fifth char on this line from 0x005c to 0x067e
	0x067E, 0x0634, 0x0630, 0x0632, 0x06CC, 0x062B, 0x0628, 0x0644, // mod the first char on this line from 0x200d to 0x067e
	0x0627, 0x0647, 0x062A, 0x0646, 0x0645, 0x067E, 0x062F, 0x062E, 
	0x062D, 0x0636, 0x0642, 0x0633, 0x0641, 0x0639, 0x0631, 0x0635, 
	0x0637, 0x063A, 0x0638, 0x007D, 0x007C, 0x007B, 0x007E            
];            



	if (!keybFarsi) {		// if keybFarsi is true, it means use the default = Iran layout
		newk = String.fromCharCode(farsikey[keyCode - 0x0020]);
	} else {
		newk = String.fromCharCode(irankey[keyCode - 0x0020]);
	}

	var objRegExp = new RegExp("[A-Za-z`0-9\x27\x2C\x3B\x5B\x5C\x5D\x7C]");
	var validate_key = objRegExp.test(String.fromCharCode(keyCode));
	if (langFarsi && ((validate_key || (keyCode==92) || (keyCode == 63)) && (keyCode != 0x200C) && (keyCode != 32)))
		if (keybFarsi) {		// Remember, if keybFarsi is true, default to Iran layout
			return { replaceKey: true, newKeyCode: irankey[keyCode - 0x0020], newKey: newk };
		} else {
			return { replaceKey: true, newKeyCode: farsikey[keyCode - 0x0020], newKey: newk };	
		}
	else
		return {cancelKey: false };
}

function changeKey (textControl, evt, keyChecker) {
  var keyCode = evt.keyCode ? evt.keyCode :
                evt.charCode ? evt.charCode :
		evt.which ? evt.which : void 0;
  var key;
  if (keyCode) {
    key = String.fromCharCode(keyCode);
  }
  var keyCheck = keyChecker(keyCode, key);
  if (keyCode && window.event && !window.opera) {
    if (keyCheck.cancelKey) {
      return false;
    }
    else if (keyCheck.replaceKey) {
      window.event.keyCode = keyCheck.newKeyCode;
      if (window.event.preventDefault) {
        window.event.preventDefault();
      }
      return true;
    }
    else {
      return true;
    }
  }
  else if (typeof textControl.setSelectionRange != 'undefined') {
    if (keyCheck.cancelKey) {
      if (evt.preventDefault) {
        evt.preventDefault();
      }
      return false;
    }
    else if (keyCheck.replaceKey) {
// cancel the key event and insert the newKey for the current selection
      if (evt.preventDefault) {
	  evt.preventDefault();
      }
      var oldSelectionStart = textControl.selectionStart;
      var oldSelectionEnd = textControl.selectionEnd;
      var selectedText = textControl.value.substring(oldSelectionStart,
oldSelectionEnd);
      var newText = typeof keyCheck.newKey != 'undefined' ?
keyCheck.newKey : String.fromCharCode(keyCheck.newKeyCode);
      textControl.value = 
        textControl.value.substring(0, oldSelectionStart) +
        newText +
        textControl.value.substring(oldSelectionEnd);
      textControl.setSelectionRange(oldSelectionStart + newText.length,
oldSelectionStart + newText.length);
      return false;
    }
    else {
      return true;
    } 
  }

  else if (keyCheck.cancelKey) {
    if (evt.preventDefault) {
      evt.preventDefault();
    }
    return false;
  }
  else {
    return true;
  }
}

function getlanguage()
{

	if (getCookie("langFarsi")) {
		langFarsi = (getCookie("langFarsi") == "true" ? true : false);
	} else {
		langFarsi = true;
	}

//	alert("Getlanguage, langFarsi = " + langFarsi);
	return (langFarsi ? BUTTON_LANG[1] : BUTTON_LANG[0]);
}

function getkeyboard()
{
	if (getCookie("keybFarsi")) {
		keybFarsi = (getCookie("keybFarsi") == "true" ? true : false);
	} else {
		keybFarsi = true;
	}
//	alert("Getkeyboard, keybFarsi = " + keybFarsi);
	return (keybFarsi ? BUTTON_KEYB[1] : BUTTON_KEYB[0]);
}

function switchlanguage()
{
	langFarsi = !langFarsi;

	var now = new Date();
	fixDate(now);
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookie('langFarsi', (langFarsi ? "true" : "false"), now, '', HOST, '');

//	alert ("Switchlanguage, langFarsi cookie = " + getCookie("langFarsi") + ", langFarsi = " + langFarsi);
	return (langFarsi ? BUTTON_LANG[1] : BUTTON_LANG[0]);
}

function switchkeyboard()
{
	keybFarsi = !keybFarsi;

	var now = new Date();
	fixDate(now);
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookie('keybFarsi', (keybFarsi ? "true" : "false"), now, '', HOST, '');

//	alert ("Switchkeyboard, keybFarsi cookie = " + getCookie("keybFarsi") + ", keybFarsi = " + keybFarsi);
	return (keybFarsi ? BUTTON_KEYB[1] : BUTTON_KEYB[0]);
}


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

// Cookie handling functions (originally from MT Comments template)
// Copyright (c) 1996-1997 Athenia Associates.
// http://www.webreference.com/js/
// License is granted if and only if this entire
// copyright notice is included. By Tomer Shiran.





function setCookie (name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function getCookie (name) {
    var prefix = name + '=';
    var c = document.cookie;
    var nullstring = '';
    var cookieStartIndex = c.indexOf(prefix);
    if (cookieStartIndex == -1)
        return nullstring;
    var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1)
        cookieEndIndex = c.length;
    return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

function deleteCookie (name, path, domain) {
    if (getCookie(name))
        document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function fixDate (date) {
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
        date.setTime(date.getTime() - skew);
}

function rememberMe (f) {
    var now = new Date();
    fixDate(now);
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
    setCookie('mtcmtauth', f.author.value, now, '', HOST, '');
    setCookie('mtcmtmail', f.email.value, now, '', HOST, '');
    setCookie('mtcmthome', f.url.value, now, '', HOST, '');
    setCookie('langFarsi', (langFarsi ? "true" : "false"), now, '', HOST, '');
    setCookie('keybFarsi', (keybFarsi ? "true" : "false"), now, '', HOST, '');
}

function forgetMe (f) {
    deleteCookie('mtcmtmail', '', HOST);
    deleteCookie('mtcmthome', '', HOST);
    deleteCookie('mtcmtauth', '', HOST);
    deleteCookie('langFarsi', '', HOST);
    deleteCookie('keybFarsi', '', HOST);
    f.email.value = '';
    f.author.value = '';
    f.url.value = '';

    langFarsi = true;
    keybFarsi = true;

    f.searchlang.value = BUTTON_LANG[1];
    f.searchkeyb.value = BUTTON_KEYB[1];
}


function OpenComments (c) {
    window.open(c,
                    'comments',
                    'width=590,height=480,scrollbars=yes,status=yes,resizable=yes');
}

function OpenTrackback (c) {
    window.open(c,
                    'trackback',
                    'width=590,height=480,scrollbars=yes,status=yes');
}


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

// Calendar / Persian Conversion Version functions

function jd_to_persian(jd)
{
    var year, month, day, daynum, depoch, cycle, cyear, ycycle,
        aux1, aux2, yday, output;


    jd = Math.floor(jd) + 0.5;

    depoch = jd - persian_to_jd(475, 1, 1);
    cycle = Math.floor(depoch / 1029983);
    cyear = mod(depoch, 1029983);
    if (cyear == 1029982) {
        ycycle = 2820;
    } else {
        aux1 = Math.floor(cyear / 366);
        aux2 = mod(cyear, 366);
        ycycle = Math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) +
                    aux1 + 1;
    }
    year = ycycle + (2820 * cycle) + 474;
    if (year <= 0) {
        year--;
    }
    yday = (jd - persian_to_jd(year, 1, 1)) + 1;
    month = (yday <= 186) ? Math.ceil(yday / 31) : Math.ceil((yday - 6) / 30);
    day = (jd - persian_to_jd(year, month, 1)) + 1;

    daynum = parseInt(mod(jd + 3, 7));

    sOutput = PERSIAN_DAYS[daynum] + " " + farsinum(String(day)) + " " + PERSIAN_MONTHS[month - 1] + " " + farsinum(String(year));
    return sOutput;
}



// **************************************************************
// Calendar routines from John Walker at http://www.fourmilab.ch/ 

function mod(a, b)

{
    
	return a - (b * Math.floor(a / b));

}



//  LEAP_GREGORIAN  --  Is a given year in the Gregorian calendar a leap year ?

function leap_gregorian(year)
{
    return ((year % 4) == 0) &&
            (!(((year % 100) == 0) && ((year % 400) != 0)));
}

//  GREGORIAN_TO_JD  --  Determine Julian day number from Gregorian calendar date

var GREGORIAN_EPOCH = 1721425.5;

function gregorian_to_jd(gyear, gmonth, gday)
{
    return (GREGORIAN_EPOCH - 1) +
           (365 * (gyear - 1)) +
           Math.floor((gyear - 1) / 4) +
           (-Math.floor((gyear - 1) / 100)) +
           Math.floor((gyear - 1) / 400) +
           Math.floor((((367 * gmonth) - 362) / 12) +
           ((gmonth <= 2) ? 0 :
                               (leap_gregorian(gyear) ? -1 : -2)
           ) +
           gday);
}

//  LEAP_PERSIAN  --  Is a given year a leap year in the Persian calendar ?

function leap_persian(year)
{
    return ((((((year - ((year > 0) ? 474 : 473)) % 2820) + 474) + 38) * 682) % 2816) < 682;
}


//  PERSIAN_TO_JD  --  Determine Julian day from Persian date

var PERSIAN_EPOCH = 1948320.5;
var PERSIAN_WEEKDAYS = new Array("Yekshanbeh", "Doshanbeh",
                                 "Seshhanbeh", "Chaharshanbeh",
                                 "Panjshanbeh", "Jomeh", "Shanbeh");

function persian_to_jd(year, month, day)
{

    var epbase, epyear;
    epbase = year - ((year >= 0) ? 474 : 473);
    epyear = 474 + mod(epbase, 2820);

    return day +
            ((month <= 7) ?
                ((month - 1) * 31) :
                (((month - 1) * 30) + 6)
            ) +
            Math.floor(((epyear * 682) - 110) / 2816) +
            (epyear - 1) * 365 +
            Math.floor(epbase / 2820) * 1029983 +
            (PERSIAN_EPOCH - 1);
}
