﻿var interval;
var searchFormVisibility = false;
var searchInputFocus = false;
var counter = 0;
var scrollStep = 10;

/********* INITIALIZE MENU ****************/

document.observe("dom:loaded", function()
{
	var searchLink = $('searchLink');
	var searchForm = $('searchForm');
	
	if (searchLink != null && searchLink != undefined) {
		searchLink.observe("mousemove", showSearchForm);
		searchLink.observe("mouseout", hideSearchForm);
	}
	
	if (searchForm != null && searchForm != undefined) {
		searchForm.observe("mousemove", showSearchForm);
		searchForm.observe("mouseout", hideSearchForm);
		
		searchFormChilderen = searchForm.childElements();
		try {
			for(i = 0; i < searchFormChilderen.length; ++i) {		
				searchFormChilderen[i].observe("mousemove", showSearchForm);
				searchFormChilderen[i].observe("mouseout", hideSearchForm);
			}
		} catch (e) {}
	}				
	
  var tabIndex = queryString("type").length > 0 ? parseInt(queryString("type")) : 0;
  if (tabIndex > 0) {				
		if (tabIndex == 9) { // there is no Shahrestanha yet and we had Vijenameha. (Shahrestanha == 8, Vijenameha == 9)
			tabIndex -= 2;
		} else {
			tabIndex--;
		}
	}
	
  setTab(tabIndex); // tab index needs zero-based index  
  
  // ---------------- blinkings --------------------
	setBlinking();
  // -----------------------------------------------
});
/******************************************/

function onSearchBlurred(e)
{
  if ((e.value == null) || (e.value.length == 0))
    e.className = 'blurred';
  else
    e.className = '';
  
  searchInputFocus = false;
  setTimeout(searchFormClose, 2000);
}

function onSearchFocused(e)
{
  e.className = 'focused';
  searchInputFocus = true;
}

function slideMenuBack()
{
  var submenu = slideMenuBack.submenu;
  var slider = slideMenuBack.slider;
  var delta = submenu.offsetWidth - slider.offsetWidth;

  if (counter < scrollStep) {
    counter++;
    if (delta > 0) {
      $("arrowPrevious").style.display = 'block';
      var left = Number(submenu.style.left.replace('px', ''));
      if ((delta - left) > 20) {
        var x = left + 20;
        submenu.style.left = x + 'px';
      }
      else {
        clearInterval(interval);
        submenu.style.left = delta + 'px';
      }
      if (submenu.style.left == delta + 'px') {
        $("arrowNext").style.display = 'none';
      }
    }
  }
  else {
    clearInterval(interval);
  }
}

function slideMenuForward() {
  var submenu = slideMenuForward.submenu;
  var slider = slideMenuForward.slider;
  var delta = submenu.offsetWidth - slider.offsetWidth;

  if (counter < scrollStep) {
    counter++;
    if (delta > 0) {
      $("arrowNext").style.display = 'block';
      var left = Number(submenu.style.left.replace('px', ''));
      if (Math.abs(left) > 20) {
        var x = left - 20;
        submenu.style.left = x + 'px';
      }
      else {
        clearInterval(interval);
        submenu.style.left = '0px';
      }
      if (submenu.style.left == "0px") {
        $("arrowPrevious").style.display = 'none';
      }
    }
  }
  else {
    clearInterval(interval);
  }
}

function scrollMenu(direction)
{
  var i;
  var slider = document.getElementById('menuSlider');
  var submenu = null;
  var submenus = slider.getElementsByTagName('div');

  for (i = 0; i < submenus.length; i++)
  {
    if (submenus[i].className == 'visible')
    {
      submenu = submenus[i];
      break;
    }
  }

  if (submenu != null)
  {
    counter = 0;
    switch (direction)
    {
      case 0:
        slideMenuBack.submenu = submenu;
        slideMenuBack.slider = slider;
        interval = setInterval('slideMenuBack()', 10);
        break;
      case 1:
        slideMenuForward.submenu = submenu;
        slideMenuForward.slider = slider;
        interval = setInterval('slideMenuForward()', 10);
        break;
    }
  }
}

function setTab(index)
{
  var submenus = document.getElementById('menuSlider').getElementsByTagName('div');	
  updateArrows(submenus[index]);
}

function updateArrows(submenu)
{
  var arrowPrevious = document.getElementById('arrowPrevious');
  var arrowNext = document.getElementById('arrowNext');
  var i, total = 0;
  var links = submenu.getElementsByTagName('a');
  var slider = document.getElementById('menuSlider');

  for (i = 0; i < links.length; i++)
    total = total + links[i].offsetWidth;

  if (slider.offsetWidth < total)
  {
    arrowPrevious.className = 'visible';
    arrowNext.className = 'visible';
  }
  else
  {
    arrowPrevious.className = 'hidden';
    arrowNext.className = 'hidden';
  }
  submenu.style.width = total + 'px';
}
            
showKeyboard = function(txt, form) {
    if ($('VirtualKeyboardContainer'))
        return;
    
    onSearchFocused(txt);

    var DivPosition = generalGetPosition($(txt));
    var container = new Element("div", {id: 'VirtualKeyboardContainer'});
    container.setStyle({position: 'absolute', width: '380px', height: '130px', border: '1px solid #c0cbdc', backgroundColor: 'white', left: DivPosition.left + 'px', top: (DivPosition.top + 20) + 'px'});
    var titleBar = new Element("div");    
    
    var close = new Element("div");
    close.update("X");
    close.onclick = function() {
        container.remove();
        onSearchBlurred(txt);
    }
    close.setStyle({float: 'right', padding: "0px 2px"});
    titleBar.appendChild(close);
    
    titleBar.setStyle({backgroundColor: '#c0cbdc', height: '20px', cursor: 'pointer', textAlign: 'center', color: 'white', fontWeight: 'bold'});
    titleBar.appendChild(new Element("span").update('صفحه كليد'));    
    container.appendChild(titleBar);
    
    var keyboardContainer = new Element("div");    
    keyboardContainer.setStyle({padding: '2px'});
    container.appendChild(keyboardContainer);        
    
    var vk = new VirtualKeyboard(txt, keyboardContainer, form);
    vk.render();
        
    new Draggable(container, {handle: titleBar});
    document.body.appendChild(container);
}

SwitchSearchForms = function(mode) {
    if (mode == 0) {
        $('frmSiteSearch').setStyle({display: ''});
        $('cse-search-box').setStyle({display: 'none'});
        $('rdSearchSite').checked = true;
        $('rdSearchWeb').checked = false;
    } else {
        $('frmSiteSearch').setStyle({display: 'none'});
        $('cse-search-box').setStyle({display: ''});
        $('rdSearchSite').checked = false;
        $('rdSearchWeb').checked = true;
    }    
}

/***********************************************************
                    BEGINING OF ARCHIVE CODES
************************************************************/

var tempImage2 = new Image();
tempImage2.src = "css/img/darklayerback.png";

showArchiveSelector = function (redirectPage) {
    // indicate loading
    
    try {
			var loadingIndicator = new Element("div");
			loadingIndicator.addClassName("archiveLoading");			
			loadingIndicator.update("در حال بارگذاري ...");
			document.body.appendChild(loadingIndicator);    
    } catch (e) {
			alert(e.message);
    }
    
    //.................
    
    
    var currentArchiveDate = queryString("year") + "/" + queryString("month") + "/" + queryString("day");

    var archiveBox = new AjaxBox("CalendarServer.aspx?callback=archiveSetdate&modify=archiveModifyDate&date=" + currentArchiveDate + "&redirectPage=" + redirectPage , {        
        darkLayerColor: "transparent",
        darkLayerOpacity: 1.0,
        style: "",
        onFetch: function() {
            this.show();
            this.container.setOpacity(0);  
            this.container.addClassName("ajaxbox");   
                        
            // extract calendar and put it in a new element and add element to the AjaxBox container
            
            var calendarTable = this.container.childElements()[0];            
            var calendarContainer = new Element("div", {id: "calendarContainer"});
            calendarContainer.appendChild(calendarTable);
                        
            //------------------------------------
            
            // customs text on top of archive
            
            var title = new Element("div");
            title.update("آرشيو نشریات").addClassName("title");            
            
            var description = new Element("div");
            description.update("لطفا تاریخ مورد نظر را انتخاب فرمایید").addClassName("description");
            
            var closeButton = new Element("div");
            closeButton.update("X").addClassName("close");
            closeButton.observe('click', closeArchiveSelector.bind(this));
            
            var board = new Element("div", {"id": "archiveBoard"});
            board.addClassName("board");
            
            this.container.appendChild(closeButton);                        
            this.container.appendChild(title);
            this.container.appendChild(description);                        
            this.container.appendChild(calendarContainer);            
            this.container.appendChild(board);
            
            this.container.setStyle({position: "fixed"});
            
            this.darkLayer.addClassName("darklayer");
            
            //------------------------------------
            
            var viewPort = document.viewport.getDimensions();
            var x = (viewPort.width - this.container.getWidth()) / 2;
            var y = (viewPort.height - this.container.getHeight()) / 2;
                 
            new Effect.Parallel([       
                new Effect.Fade(this.container, { duration: 1.0, from: 0, to: 1 }),
                new Effect.Move(this.container, { x: x, y: y, mode: 'relative' })
            ]);
            
            loadingIndicator.remove();
        }
    });     
}

closeArchiveSelector = function() {
    this.remove();
}

archiveSetdate = function (date, redirectPage) {
  if (redirectPage == undefined || redirectPage == NaN || redirectPage == null)
    redirectPage = "Default.aspx";

  var dateParts = date.split('/');

  var board = $('archiveBoard');
  board.update('در حال دريافت اطلاعات ...');

  var publicationType = queryString("type").length > 0 ? queryString("type") : "1";

  new Ajax.Request("action/web2/GetSerialByDateAndType.aspx", {
    method: "get",
    parameters: {
      year: "13" + dateParts[0],
      month: dateParts[1],
      day: dateParts[2]
    },
    onSuccess: function (transport) {
      var xml = transport.responseXML;
      if (xml != null && xml != undefined) {
        var elmSerial = xml.documentElement;
        var serial = parseInt(elmSerial.childNodes[0].nodeValue);
        if (serial > 0) {
//          var url = document.location.href;
//          url = url.substring(0, url.indexOf('?'));

//          var urlParts = url.split('/');
//          var urlFileName = urlParts[urlParts.length - 1];

//          if (urlFileName != "PDFNews.aspx")
            url = redirectPage;

          if (publicationType < 10)
            var newUrl = url + "?type=" + publicationType + "&year=13" + dateParts[0] + "&month=" + dateParts[1] + "&day=" + dateParts[2];
          document.location.href = newUrl;
        } else {
          board.update('متاسفانه در این تاريخ نشریه مورد نظر وجود ندارد');
          new Effect.Highlight(board);
        }
      }
    }
  });
}

archiveModifyDate = function (date, redirectPage, yearStep, monthStep) {
  new Ajax.Updater('calendarContainer', 'CalendarServer.aspx?redirectPage=' + redirectPage, {
    parameters: {
      callback: "archiveSetdate",
      modify: "archiveModifyDate",
      date: date,
      year: yearStep,
      month: monthStep
    }
  });
}    

/***********************************************************
                    END OF ARCHIVE CODES
***********************************************************/

/***********************************************************
                 BEGININF OF SEARCH CODES
***********************************************************/

showSearchForm = function() {
	searchFormVisibility = true;
	var searchForm = $('searchForm');
	searchForm.setStyle({visibility: 'visible', display: 'block'});	
}

hideSearchForm = function() {
	searchFormVisibility = false;
	setTimeout(searchFormClose, 2000);
}

searchFormClose = function() {
	if (searchInputFocus || searchFormVisibility)
		return;
	var searchForm = $('searchForm');
	new Effect.Fade(searchForm, {duration: 0.7});
}

/***********************************************************
                    END OF SEARCH CODES
***********************************************************/


queryString = function(key) {
    var url = document.location.toString();   
    if (url.indexOf('#') > -1) 
			url = url.substring(0, url.indexOf('#'));
    var queryString = url.substring(url.indexOf('?') + 1);
    var params = queryString.split('&');
        
    for (i = 0; i < params.length; ++i) {
        var tmpArray = params[i].split('=');
        if (tmpArray[0] == key)
            return tmpArray[1];
    }
    
    return "";    
}

generalGetPosition = function (element){
  var valueT = 0, valueL = 0;
	try
	{
		do {
				 valueT += element.offsetTop  || 0;
				 valueL += element.offsetLeft || 0;
				 element = element.offsetParent;
				} while (element);
			return {left: valueL, top: valueT};
	}
	catch(err)
	{
			return {left:valueL, top: valueT};
	}		
}

condolence = function(pdf15) {	
	window.open(pdf15);
}

/******************************** REPORT BUG ***************************************/
var reportBox;
reportBug = function() {
	reportBox = new AjaxBox("ReportBug.aspx?ts=" + new Date().toString(), {
		darkLayerColor: "transparent",
    darkLayerOpacity: 1.0,
    eval: true,
    onFetch: function() {
			this.show();
      this.container.setOpacity(0);  
      this.container.addClassName("ajaxbox");                          
                  
      //------------------------------------
      
      // customs text on top of archive
      
      var title = new Element("div");
      title.update("گزارش خطا").addClassName("title");            
                  
      var closeButton = new Element("div");
      closeButton.update("X").addClassName("close");
      closeButton.observe('click', closeArchiveSelector.bind(this));            
      this.container.insertBefore(closeButton, this.container.firstChild);                        
      
      this.container.setStyle({position: "fixed"});
      
      this.darkLayer.addClassName("darklayer");
      
      //------------------------------------
      
      var viewPort = document.viewport.getDimensions();
      var x = (viewPort.width - this.container.getWidth()) / 2;
      var y = (viewPort.height - this.container.getHeight()) / 2;
           
      new Effect.Parallel([       
          new Effect.Fade(this.container, { duration: 1.0, from: 0, to: 1 }),
          new Effect.Move(this.container, { x: x, y: y, mode: 'relative' })
      ]);
    }
	});			
}

sendReportBug = function() {

	var txtBugUrl = $('bugUrl');
	var txtBugDescription = $('bugDescription');
	var board = $('bugBoard');
	
	var url = txtBugUrl != undefined ? txtBugUrl.value : "";
	var description = txtBugDescription != undefined ? txtBugDescription.value : "";
	
	//sending...
	
	if (board != undefined) {
		board.update('در حال ارسال ...').setStyle({color: 'blue'});
	}
	
	new Ajax.Request('action/web2/ReportBug.aspx', {
		method: 'post',
		parameters: {url: url, description: description},
		onSuccess: function(transport) {
			var result = transport.responseText;
			if (result == 'success') {
				board.update('با تشكر از توجه شما').setStyle({color: 'green'});
				setTimeout('reportBox.remove();', 2000);
			} else {
				board.update(result).setStyle({color: 'black'});
			}
		}
	});
	
}

/************************************* BLINKING LINKS ******************************/

var blinkings = null;

setBlinking = function(element) { // options.onClass = "css class"   - options.offClass = "css class"
  if (blinkings == null) {
    blinkings = $$(".blink");
  }
  for (var i = 0; i < blinkings.length; ++i) {
    var blinking = blinkings[i];

    var rel = blinking.rel;
    var onClass = "";
    var offClass = "";
    if (rel != null && rel != undefined) {
      var tempArray = rel.split(" ");
      if (tempArray.length > 1) {
        onClass = tempArray[0];
        offClass = tempArray[1];
      }
    }
    if (Prototype.Browser.IE) {
      if (blinking.hasClassName(offClass)) {
        blinking.removeClassName(offClass);
        blinking.addClassName(onClass);
      } else {
        blinking.addClassName(offClass);
        blinking.removeClassName(onClass);
      }
    } else {
      if (blinking.getOpacity() == '1') {
        blinking.setOpacity(0.5);
      } else {
        blinking.setOpacity(1);
      }
    }
  }
  setTimeout(setBlinking, 500);
}


//******************************

GRShare = function() {
	var b=document.body;
	var GR________bookmarklet_domain='http://www.google.com';
	if(b && !document.xmlVersion) {
		void(z=document.createElement('script'));
		void(z.src='http://www.google.com/reader/ui/link-bookmarklet.js');
		void(b.appendChild(z));
	} else {}
}

/****************** PreLoader *****************************/
var CurrentTimeShow = null;
PreLoader = function() {
  if (CurrentTimeShow == null) {
    try {
      var loadingIndicator = new Element("div");
      loadingIndicator.addClassName("PreLoading");
      loadingIndicator.update('<table width="100%" class="PreLoading"><tr><td width="45%" class="Opacity">&nbsp;</td><td class="Title">در حال بارگذاري ...</td><td width="45%"  class="Opacity">&nbsp;</td></tr></table>');

      document.body.appendChild(loadingIndicator);
      CurrentTimeShow = true;
    } catch (e) {
      alert(e.message);
    }
  }
}

