/* cookie */
$.cookie = {
	set: function(key, val, exp) {
		val = encodeURIComponent(val) + '; path=/';
		if (exp) {
			var date = new Date();
			date.setTime(date.getTime() + exp * 24 * 60 * 60 * 1000);
			val += '; expires=' + date.toGMTString();
		}
		document.cookie = key + '=' + val;
	},
	get: function(key) {
		var val = document.cookie.match('(?:^|;)\\s*' + key + '=([^;]*)');
		return (val) ? decodeURIComponent(val[1]) : null;
	},
	del: function(key) {
		this.set(key, this.get(key), -1);
	}
};

/* cufon */
$.fn.cufon = function () {
	$(this).find('H1,H2,H3,.cufon').each(function() {
		var obj = $(this);
		Cufon.replace(obj, { fontFamily: 'Neo Sans Pro Light', fontSize: obj.css('fontSize') });
	});
	$(this).find('H4,.cufon4').each(function() {
		var obj = $(this);
		Cufon.replace(obj, { fontFamily: 'Neo Sans Pro', fontSize: obj.css('fontSize') });
	});
	return this;
}

$.default_font = function (element) {
  element = $(element);
  
  // Шрифт по умолчанию
  var font = element.css ("font-family");

  if (element.is ("H1, H2, H3, .cufon")) {
    font = "Neo Sans Pro Light";
  }
  else if (element.is ("H4, .cufon4")) {
    font = "Neo Sans Pro";
  }
  
  return font;
}

$.fn.font = function (font) {
  if ($.isFunction (font)) {
    font = font (this);
  }
  
  $(this).add ($(this).find ("*")).each (function () {
    Cufon.replace ($(this), { fontFamily: font, fontSize: $(this).css ("fontSize") });
  });
 
  return this;
}

/* carousel */
$.fn.carousel = function() {
	var c = $(this);
	c.find('.carousel-wrap').jCarouselLite({
		visible: 5,
		scroll: 2,
		btnPrev: c.find('.carousel-prev'),
		btnNext: c.find('.carousel-next')
	});
	var lis = c.find('LI').click(function() {
		lis.removeClass('active');
		c.children('INPUT').val($(this).addClass('active').find('INPUT').val());
	});
	return c;
}

/* forms */
$.fn.forms = function() {
	var f = $(this);
	f.find('.ls-text').append('<b/><i/>');
	var list = !$('#ls-select-list');
	if (!list.length)
		list = $('<div id="ls-select-list"/>').appendTo('BODY').hide();
	f.find('.ls-select').each(function() {
		$(this).select(list);
	});
	f.find('.ls-area').wrapInner('<div class="wrap"/>').prepend('<div class="tp"><b></b><i></i></div>').append('<div class="bt"><b></b><i></i></div>');
	f.find('INPUT[type=radio]').each(function() {
		$(this).radiobtn();
	});
	return f;
}

/* select */
$.fn.select = function(list) {
	var s = $(this), sel = s.find('SELECT'), timer = null;
	var html = '';
	var opts = sel.find('OPTION').each(function() {
		var o = $(this);
		html += '<li' + (o.attr('disabled') ? ' class="disabled"><span></span>' : '>') + o.text() + '</li>';
	});
	html = '<ul>' + html + '</ul>';
	var txt = $('<div/>').appendTo(s).text(opts.filter(':selected').text());
	s.find('I').click(function() {
		if (list.css('display') == 'none') {
			list.html(html).find('LI').click(function() {
				var o = $(this);
				txt.text(o.text());
				opts.eq(o.index()).attr('selected', 'selected');
				sel.triggerHandler('change');
				list_hide();
			}).eq(s.find(':selected').index()).addClass('selected');
			var p = s.offset();
			list.css({ 'top': p.top + s.height(), 'left': p.left + 3 }).width(s.outerWidth()-8).show();
            list.add(s).bind('mouseover', function() {
            	clearTimeout(timer);
            }).bind('mouseout', function() {
	      		timer = setTimeout(function() {
  	    	 		list_hide();
		   	   	}, 150);
            });
		} else list_hide();
	});
	function list_hide() {
		list.hide().add(s).unbind('mouseover').unbind('mouseout');
	}
    return s;
}

/* radio buttons */
$.fn.radiobtn = function() {
	var c = $(this).wrap('<span class="ls-radio"/>'), b = c.parent();
	var trigger = b.parent().get(0).tagName.toLowerCase() == 'label' ? b.parent() : b;
	trigger.click(function() {
		if (!c.attr('checked')) {
			$('INPUT[name=' + c.attr('name') + ']').not(c).each(function() {
				$(this).attr('checked', false).parent().removeClass('check');
			});
			c.attr('checked', true); b.addClass('check');
		}
	});
	if (c.attr('checked')) b.addClass('check');
	return c;
}

/* for ie: text-shadow, rounded corners */
$.fn.ie_css3 = function() {
	var c = $(this);
	if (!-[1,]) {
		c.find('.shadow').textShadow();
		c.find('.corners').addClass('ie').each(function() {
			$(this).wrapInner('<div class="wrap clrfix"/>')
				.prepend('<div class="cr"><div class="tr"></div><div class="tl"></div></div>')
					.append('<div class="cr"><div class="br"></div><div class="bl"></div></div>');
		});
	}
	return c;
}

/* flash */
$.fn.flash = function (on_load) {
  this.each (function () {
    var f = $(this);

    var flash_path = f.find ("span.file-path").text ();
    var flash_width = f.find ("span.width").text () || "100%";
    var flash_height = f.find ("span.height").text ();
    var flash_height_ratio = parseFloat (f.find ("span.height-ratio").text ());
    var variables = {}
    
    $.each (f.find ("span.variables").children ("var"), function (i, v) {
      variables [v.className] = $(v).text ();
    });
    
    var height = null;
    
    if (flash_height_ratio) {
      height = parseInt (f.parent ().width () * (flash_height_ratio || 1));
    } else {
      height = flash_height || "100%";
    }

    swfobject.embedSWF (
        flash_path                        // swfUrlStr
      , f.attr ("id")                     // replaceElemIdStr
      , flash_width                       // widthStr
      , height                            // heightStr
      , "10"                              // swfVersionStr
      , "swf/expressInstall.swf"          // xiSwfUrlStr
      , variables                         // flashvarsObj
      , { "wmode" : "opaque" }            // parObj
      , {}                                // attObj
      , on_load                           // callbackFn
    );
  	
    var resize_timer = null;
  });
  
  return this;
}

/* param deserealization */
$.unparam = function (value) {
  var
  // Object that holds names => values.
  params = {},
  // Get query string pieces (separated by &)
  pieces = value.split('&'),
  // Temporary variables used in loop.
  pair, i, l;

  // Loop through query string pieces and assign params.
  for (i = 0, l = pieces.length; i < l; i++) {
      pair = pieces[i].split('=', 2);
      // Repeated parameters with the same name are overwritten. Parameters
      // with no value get set to boolean true.
      params[decodeURIComponent(pair[0])] = (pair.length == 2 ?
          decodeURIComponent(pair[1].replace(/\+/g, ' ')) : true);
  }

  return params;
};

$(function() {
  $('BODY').cufon().forms().ie_css3();

  /* embed flash */
  $(".flash:visible").flash ();
  
  /* init menu */
  Menu.init ();
  
  /* automatically unpin menu if window height is too big */
	$(window).resize (function () {
	  if ($("#container").innerHeight () < $(window).height ()) {
	    Menu.unpin ();
	    Menu.lock ();
	  }
	  else {
	    // reset menu state
	    Menu.unlock ();
	  }
	}).resize ();
  
  $("#lnav").font ("Neo Sans Pro");

  /* Colour Futures icon */
  $("#lnav a:contains('Colour Futures')")
    .attr ("id", "colour-futures")
    .attr ("target", "_blank")
    .html ("<img src='img/colour_futures.png' alt='Colour Futures' />");
    
  /* Professionals icons */
  $("#lnav a:contains('Акзо Нобель')")
    .attr ("id", "akzo-nobel")
    .html ("<img src='img/akzo-nobel.jpg' alt='Акзо Нобель' />");

  $("#lnav a:contains('ARCHiPEOPLE.ru')")
    .attr ("id", "archipeople")
    .html ("<img src='img/archipeople.jpg' alt='ARCHiPEOPLE.ru' />");
    
  /* Lets colour news */
  $("#lnav a:contains('Новости')")
    .parent()
    .attr ("id", "lets-colour-news");
});
