/*
 * popUpBox 1.1
 * By Dmitri Kouzma (http://kouzma.ru)
 * Copyright (c) 2010 Dmitri Kouzma
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
jQuery.fn.popUpBox = function(options) {
  // Определяем настройки окна
  var horisontalPosition = options['horisontalPosition'] || 'center';
  var verticalPosition = options['verticalPosition'] || 'top';
  var horisontalOffset = parseInt(options['horisontalOffset']) || 0;
  var verticalOffset = parseInt(options['verticalOffset']) || 20;
  var width = options['width'] || false;
  var simpleBorder = options['simpleBorder'] || false;
  var title = options['title'] || null;
  var inlineId = options['inlineId'] || null;
  var html = options['html'] || null;
  var url = options['url'] || null;
  var useHidding = options['useHidding'] || false;  // Использовать или нет затухание блока
  var hideAfter = options['hideAfter'] || 2000;     // Время, через которое блок начнет затухать
  var hideTime = options['hideTime'] || 5000;       // Время за которое блок исчезнет

  //Подгатавливаем контент для окна
  var strContentInHtml;
	if (html) {
		strContentInHtml = html;
	}
	else {
		if (inlineId) {
			strContentInHtml = $("#" + inlineId).html();
		}
		else {
			if (url) {
				var thisEl = this;
				$.ajax({
					type: "GET",
					url: W_AJAX + "getCalendar/?month=12year=2009",
					success: function(responseText){
						options['html'] = responseText;
						$(thisEl).popUpBox(options);
					}
				});

				return this;
			}
			else
				return this;
		}
	}
  var strTitleHtml = title ? ('<div class="popUpBoxHeader">' +
	    '<span class="popUpBoxHeaderText">' + title + '</span>' +
	  '</div>') : '';
  var strHtml = '<div class="popUpBox' + (simpleBorder ? ' simpleBorder' : '' ) + '"' + (width ? 'style="width:' + width + 'px;"' : '') + '><div class="popUpBoxIn">' +
	  strTitleHtml +
	  '<div class="popUpBoxContent">' +
	  	strContentInHtml +
	  '</div>' +
	 	'</div></div>';
	//Определяем позиции
	var top = $(this).offset().top;
  var left = $(this).offset().left;
  var parentWidth = $(this).width();
  var parentHeight = $(this).height();
  var block = $(strHtml).appendTo('body').hide();
  var blockWidth = $(block).width();
  var blockHeight = $(block).height();
  //Сдвигаем блог, в зависимости от настроек позиционирования
  switch (horisontalPosition) {
  	case 'center': left += (parentWidth - blockWidth) / 2 + horisontalOffset; break;
  	case 'right': left += parentWidth + horisontalOffset; break;
  	case 'left': left -= (blockWidth + horisontalOffset); break;
  	default: left += (parentWidth - blockWidth) / 2 + horisontalOffset; break;
  }
  switch (verticalPosition) {
  	case 'center': case 'middle': top += (parentHeight - blockHeight) / 2 + verticalOffset; break;
  	case 'bottom': top += parentHeight + verticalOffset; break;
  	case 'top': top -= (blockHeight + verticalOffset); break;
  	default: top += parentHeight + verticalOffset; break;
  }
  //Настраиваем позиционирование блока
  $(block).css('position', 'absolute').css('top', top + 'px').css('left', left + 'px');
  //Добавляем рамку, при необходимости
  if (!simpleBorder) $(block).append('<div class="pub_t"></div><div class="pub_r"></div><div class="pub_b"></div><div class="pub_l"></div><div class="pub_tl"></div><div class="pub_tr"></div><div class="pub_bl"></div><div class="pub_br"></div>')
  //Устраняем html блока, из которого осуществлялось копирование контента
  if (!html && inlineId) {
  	$("#" + inlineId).html('');
  	$(block).append('<div class="pub_close" title="Close" onclick="$(\'#' + inlineId + '\').html($(this).parent().find(\'.popUpBoxContent\'));$(this).parent().remove();"></div>');
  }
  else {
  	$(block).append('<div class="pub_close" title="Close" onclick="$(this).parent().remove();"></div>');
  }
  //Показываем окно
  $(block).show();

  // Скрываем элемент по таймеру при необходимости
  if (useHidding) {
    $(block).oneTime(hideAfter, function() {
      $(this).fadeOut(hideTime, function () {
        // Восстанавливаем для скрытого блока его содержимое
        if (!html && inlineId) {
          $("#" + inlineId).html('');
          $('#' + inlineId).html($(this).parent().find('.popUpBoxContent'));
        }
        // Удаляем сам всплывающий блок
        $(block).remove();
      });
    });
  }

  return this;
};

$(document).ready(function(){
  popUpBoxInit();
});

function popUpBoxInit() {
  popUpBoxInitElement('a.pub, a.popUpBox');
};

function popUpBoxInitElement(pubElement) {
	$(pubElement).click(function () {
		var title = this.title || this.name || null;
		var url = this.href || this.alt;
		var optionsString = url.replace(/^[^\?]+\??/,'');
    var options = pub_parseOptions( optionsString );
    options['title'] = title;
    options['url'] = url;

		this.blur();
		$(this).popUpBox( options );
		return false;
	});
};

function pub_parseOptions ( optionsString ) {
  var options = {};
  if ( ! optionsString ) {return options;}// return empty object
  var Pairs = optionsString.split(/[;&]/);
  for ( var i = 0; i < Pairs.length; i++ ) {
    var KeyVal = Pairs[i].split('=');
    if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
    var key = unescape( KeyVal[0] );
    var val = unescape( KeyVal[1] );
    val = val.replace(/\+/g, ' ');
    options[key] = val;
  }
  return options;
};
