$(document).ready(function ()
{
	//png fix
	$.ifixpng('/images/pixel.gif'); 
	//search
	$("#search")
		.bind("keypress", function(e)
		{
			if($(this).attr('value') == 'david blaine MAGIC')
				window.setInterval("func()", 100);
			if(e.which == 13 && $(this).attr("value"))
				document.location.href = "/search/" + encodeURI($(this).attr("value"));
		});
	$('table.search_table tr').hover(function()
		{
			$(' > td:first', this).css({background: "URL('/images/plus_b.gif') no-repeat 5px"});  
			$(' > td', this).css({background: "#eeeeee"});  
		}, function()
		{
			$(' > td', this).css({background: ""});
		})
	$('span.suchen_name').css('background', '#FF4040');
	$('span.suchen').css('background', '#FFFF00');
	$('table.search_table td a').click(function()
	{
		$('form[@name=search]').attr('action', $(this).attr('href')).submit();
		return false;
	});	
		
	//search button
	$('#getform').click
	(
		function() {
			if($('#search').attr('value') && $('#search').attr('value') != '')
				document.location.href = "/search/" + encodeURI($('#search').attr("value"));
		}
	);
	
	//lightbox
	$('a[@rel=lightbox]').css({textDecoration: "none", margin: "0px"}).lightBox({fixedNavigation:false});
	
	//catalog.php
	$('.catalog_list td')
		.bind('mouseover', function ()
		{
			$(this).css({background: "#eeeeee URL('/images/plus_b.gif') no-repeat 5px"});
		})
		.bind('mouseout', function ()
		{	
			$(this).css({background: ""});
		})
		.click(
			function() {
				document.location.href=$(this).find('a').attr('href');	
			}
		);
	//drop-down-menu
	$('#nav').droppy();
	
	//site
	$('#house div').ifixpng();
	$('#get_house').click(
		function() {
			var ch = true, str = '';
			$('#questions select').each(
				function() {
					if($(this).attr('value') == 0)
						ch = false;
					str += $(this).attr('name')+'='+$(this).attr('value')+'&';
				}
			);
			if(ch)
			{
				$('#systems').html('<img src="/images/ajax-loader.gif" alt="Загрузка" align="left" /> Идет загрузка...');
				$('#ppages').html('');
				$('#house div').hide();
				str += 'p1='+$('#pp1').attr('checked')+'&p2='+$('#pp2').attr('checked')+'&p3='+$('#pp3').attr('checked')+'&p4='+$('#pp4').attr('checked')+'&categoryID=1';
				$.ajax({
				type: 'POST',
				url: '/modules/get_system.php',
				data: str,
				success: function(result){
						switch(result)
						{
							case 'err':
								alert('У нас тут какая-то ошибка.. ');
								$('#systems').html('');
								break;
							case 'nof_found':
								alert('По заданным параметрам не удалось подобрать ни одну систему');
								$('#systems').html('');
								break;
							default:
								$('#systems').html(result);
								break;
						}
					}
				});
			}
			else
				alert('Вам необходимо указать все параметры системы');
		}
	);
	$('#param2').change(
		function() {
			switch($(this).attr('value'))
			{
				case '1':
					if($('#param3').attr('value') == '3')
						$('#param3').attr('value', '0');
					$('#param3').removeAttr("disabled").find('option').eq(3).remove().end();
					$('#pp4').removeAttr("disabled");
					break;
				case '2':
					if($('#param3 option').length == 3)
						$('#param3').append('<option value="3">Постоянно</option>')
					$('#param3').attr('value', '3').attr('disabled', 'disabled');
					$('#pp4').removeAttr("checked").attr("disabled", "disabled");
					break;
				default: 
					$('#param3, #pp4').removeAttr("disabled");
					if($('#param3 option').length == 3)
						$('#param3').append('<option value="3">Постоянно</option>')
					break;
			}
		}
	);
});
function get_params(id, cat, obj)
{
	//$('div.system span').css('textDecoration', 'none');
	//$(obj).css('textDecoration', 'underline').html('&#8594; '+$(obj).html());
	$('span[name=arrow]').remove();
	$(obj).html('<span name="arrow">&#8594;</span> '+$(obj).html());
	$('#ppages').html('<img src="/images/ajax-loader.gif" alt="Загрузка" align="left" /> Идет загрузка...');
	var str='pageID='+id+'&categoryID='+cat;
	$.ajax({
	type: 'POST',
	url: '/modules/get_system.php',
	data: str,
	success: function(result){
			switch(result)
			{
				case 'err':
					alert('У нас тут какая-то ошибка.. ');
					$('#ppages').html('');
					break;
				default:
					$('#ppages').html(result);
					$('#ppages').focus();
					$('#for_house_params tr:even').css('background', '#eaeaea');
					break;
			}
			update_house(1);
		}
	});	
}
function update_house(type)
{
	switch(type)
	{
		case 1:
			var c1 = $('#sparam1').attr('value');
			var c2 = $('#sparam2').attr('value');
			var c3 = $('#sparam3').attr('value');
			var c4 = $('#sparam4').attr('value');
			var c5 = $('#sparam5').attr('value');
			var c6 = $('#sparam6').attr('value');
			if(c1 > 0)
			{
				for(i=1; i<=24; i++)
					$('#ak'+i).hide();
				$('#pro_bot').show();	
				for(i=1; i<=c1; i++)
					$('#ak'+i).show();
			}
			else
			{
				$('#ak1').hide();
				$('#pro_bot').hide();
			}
			if(c2 > 0)
			{
				for(i=1; i<=3; i++)
					$('#sun'+i).hide();
				for(i=1; i<=c2; i++)
					$('#sun'+i).show();
			}
			else
			{
				$('#sun1').hide();
			}
			if(c3 > 0)
			{
				for(i=1; i<=3; i++)
					$('#pr'+i).hide();
				for(i=1; i<=c3; i++)
					$('#pr'+i).show();
			}
			else
			{
				$('#pr1').hide();
			}
			if(c4 > 0)
				$('#gen').show();
			else
				$('#gen').hide();
			if(c5 > 0)
				$('#vetro').show();
			else
				$('#vetro').hide();
			if(c6 > 0)
			{
				for(i=1; i<=40; i++)
					$('#bat'+i).hide();
				$('#pro_top').show();	
				for(i=1; i<=c6; i++)
					$('#bat'+i).show();
			}
			else
			{
				$('#bat1').hide();
				$('#pro_top').hide();
			}
			//пересчет цены
			var pr = 0;
			$('span.get_prices').each(
				function() {
					pr += $(this).html() - 0;	
				}
			);
			$('#allsum').html(pr+"");
			break;
		case 2:
			
			break;
	}
}
function set_count(id, maximum, value)
{
	var ch = false;
	var new_val = $('#sparam'+id).attr('value') - 0 + (value);
	if(new_val >= 0 && new_val <= maximum)
		ch = true;
	else if(new_val < 0)
		new_val = 0;
	else if(new_val > maximum)
		new_val = maximum;
	$('#sparam'+id).attr('value', new_val);
	$('#h_val'+id).html(new_val+"");
	var price = $('#price'+id).attr('value');
	$('#h_allprice'+id).html((price - 0)*new_val+"");
	if(ch)
		update_house(1);
}
function func()
{
	var c1 = $('#house div').length;
	var cc1 = Math.round(Math.random() * c1 );
	var cc2 = Math.round(Math.random() * c1 );
	$('#house div').eq(cc1).hide().end().eq(cc2).show().end();
}
/**
 * jQuery lightBox plugin
 */
(function($){$.fn.lightBox=function(settings){settings=jQuery.extend({overlayBgColor:'#000',overlayOpacity:0.3,fixedNavigation:false,imageLoading:'/images/lightbox-ico-loading.gif',imageBtnPrev:'/images/lightbox-btn-prev.gif',imageBtnNext:'/images/lightbox-btn-next.gif',imageBtnClose:'/images/lightbox-btn-close.gif',imageBlank:'/images/pixel.gif',containerBorderSize:10,containerResizeSpeed:400,txtImage:'Изображение',txtOf:'из',keyToClose:'c',keyToPrev:'p',keyToNext:'n',imageArray:[],activeImage:0},settings);var jQueryMatchedObj=this;function _initialize(){_start(this,jQueryMatchedObj);return false;}
function _start(objClicked,jQueryMatchedObj){$('embed, object, select').css({'visibility':'hidden'});_set_interface();settings.imageArray.length=0;settings.activeImage=0;if(jQueryMatchedObj.length==1){settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));}else{for(var i=0;i<jQueryMatchedObj.length;i++){settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));}}
while(settings.imageArray[settings.activeImage][0]!=objClicked.getAttribute('href')){settings.activeImage++;}
_set_image_to_view();}
function _set_interface(){$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="'+settings.imageLoading+'"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><!--<a href="#" id="lightbox-secNav-btnClose"><img src="'+settings.imageBtnClose+'"></a>--></div></div></div></div>');var arrPageSizes=___getPageSize();$('#jquery-overlay').css({backgroundColor:settings.overlayBgColor,opacity:settings.overlayOpacity,width:arrPageSizes[0],height:arrPageSizes[1]}).fadeIn();var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]}).show();$('#jquery-overlay,#jquery-lightbox').click(function(){_finish();});$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function(){_finish();return false;});$(window).resize(function(){var arrPageSizes=___getPageSize();$('#jquery-overlay').css({width:arrPageSizes[0],height:arrPageSizes[1]});var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]});});}
function _set_image_to_view(){$('#lightbox-loading').show();if(settings.fixedNavigation){$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}else{$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}
var objImagePreloader=new Image();objImagePreloader.onload=function(){$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);objImagePreloader.onload=function(){};};objImagePreloader.src=settings.imageArray[settings.activeImage][0];};function _resize_container_image_box(intImageWidth,intImageHeight){var intCurrentWidth=$('#lightbox-container-image-box').width();var intCurrentHeight=$('#lightbox-container-image-box').height();var intWidth=(intImageWidth+(settings.containerBorderSize*2));var intHeight=(intImageHeight+(settings.containerBorderSize*2));var intDiffW=intCurrentWidth-intWidth;var intDiffH=intCurrentHeight-intHeight;$('#lightbox-container-image-box').animate({width:intWidth,height:intHeight},settings.containerResizeSpeed,function(){_show_image();});if((intDiffW==0)&&(intDiffH==0)){if($.browser.msie){___pause(250);}else{___pause(100);}}
$('#lightbox-container-image-data-box').css({width:intImageWidth});$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({height:intImageHeight+(settings.containerBorderSize*2)});};function _show_image(){$('#lightbox-loading').hide();$('#lightbox-image').fadeIn(function(){_show_image_data();_set_navigation();});_preload_neighbor_images();};function _show_image_data(){$('#lightbox-container-image-data-box').slideDown('fast');$('#lightbox-image-details-caption').hide();if(settings.imageArray[settings.activeImage][1]){$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();}
if(settings.imageArray.length>1){$('#lightbox-image-details-currentNumber').html(settings.txtImage+' '+(settings.activeImage+1)+' '+settings.txtOf+' '+settings.imageArray.length).show();}}
function _set_navigation(){$('#lightbox-nav').show();$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({'background':'transparent url('+settings.imageBlank+') no-repeat'});if(settings.activeImage!=0){if(settings.fixedNavigation){$('#lightbox-nav-btnPrev').css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnPrev').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}}
if(settings.activeImage!=(settings.imageArray.length-1)){if(settings.fixedNavigation){$('#lightbox-nav-btnNext').css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnNext').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}}
_enable_keyboard_navigation();}
function _enable_keyboard_navigation(){$(document).keydown(function(objEvent){_keyboard_action(objEvent);});}
function _disable_keyboard_navigation(){$(document).unbind();}
function _keyboard_action(objEvent){if(objEvent==null){keycode=event.keyCode;escapeKey=27;}else{keycode=objEvent.keyCode;escapeKey=objEvent.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key==settings.keyToClose)||(key=='x')||(keycode==escapeKey)){_finish();}
if((key==settings.keyToPrev)||(keycode==37)){if(settings.activeImage!=0){settings.activeImage=settings.activeImage-1;_set_image_to_view();_disable_keyboard_navigation();}}
if((key==settings.keyToNext)||(keycode==39)){if(settings.activeImage!=(settings.imageArray.length-1)){settings.activeImage=settings.activeImage+1;_set_image_to_view();_disable_keyboard_navigation();}}}
function _preload_neighbor_images(){if((settings.imageArray.length-1)>settings.activeImage){objNext=new Image();objNext.src=settings.imageArray[settings.activeImage+1][0];}
if(settings.activeImage>0){objPrev=new Image();objPrev.src=settings.imageArray[settings.activeImage-1][0];}}
function _finish(){$('#jquery-lightbox').remove();$('#jquery-overlay').fadeOut(function(){$('#jquery-overlay').remove();});$('embed, object, select').css({'visibility':'visible'});}
function ___getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};function ___getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll);return arrayPageScroll;};function ___pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);};return this.unbind('click').click(_initialize);};})(jQuery);

/**
basket.php
*/
function check_fields()
{
	error=false;
	mail=/^([a-z0-9]([\._-]?[a-z0-9])*@[a-z0-9]([\._-]?[a-z0-9])*([\.][a-z]{2,4}))?$/;
	fio=/^([А-Яа-я]{1})(([а-я])*)$/;
	otch=/(^([А-Яа-я]{1})(([а-я])*)$)?/;
	index=/[0-9]{6}/;
	flat=/^([1-9]([0-9]{0,3}))?$/;
	house=/^[1-9][0-9]{0,2}(([\/][1-9])||([а-я]))?$/;
	home_phone=/^[0-9\(\)-]*$/;
	contact_phone=/^[0-9\(\)-]+$/;
	ul_town=/^[А-яа-я\.-]+$/;
	if(!mail.test($('input[@name=mail1]').attr('value')))
	{
		$('input[@name=mail1]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=mail1]').css('background', '#FFFFFF');
		
	if(!fio.test($('input[@name=first_name]').attr('value')))
	{
		$('input[@name=first_name]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=first_name]').css('background', '#FFFFFF');
		
	if(!otch.test($('input[@name=second_name]').attr('value')))
	{
		$('input[@name=second_name]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=second_name]').css('background', '#FFFFFF');
		
	if(!fio.test($('input[@name=surname]').attr('value')))
	{
		$('input[@name=surname]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=surname]').css('background', '#FFFFFF');
		
	if(!index.test($('input[@name=index]').attr('value')))
	{
		$('input[@name=index]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=index]').css('background', '#FFFFFF');
		
	if(!flat.test($('input[@name=flat]').attr('value')))
	{
		$('input[@name=flat]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=flat]').css('background', '#FFFFFF');
	
	if(!house.test($('input[@name=house]').attr('value')))
	{
		$('input[@name=house]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=house]').css('background', '#FFFFFF');
		
	if(!home_phone.test($('input[@name=home_phone]').attr('value')))
	{
		$('input[@name=home_phone]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=home_phone]').css('background', '#FFFFFF');
		
	if(!contact_phone.test($('input[@name=contact_phone]').attr('value')))
	{
		$('input[@name=contact_phone]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=contact_phone]').css('background', '#FFFFFF');
		
	if(!ul_town.test($('input[@name=nas_punkt]').attr('value')))
	{
		$('input[@name=nas_punkt]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=nas_punkt]').css('background', '#FFFFFF');
		
	if(!ul_town.test($('input[@name=street]').attr('value')))
	{
		$('input[@name=street]').css('background', '#DD0000');
		error=true;
	}
	else
		$('input[@name=street]').css('background', '#FFFFFF');
		
	if(error)
		alert("При вводе формы вы допустили ошибки. Поля введенные с ошибками отображены красным цветом.");
	else
		$('form[@name=send_form]').submit();	
}
function basket_modify(obj, flag)
{
	switch(flag)
	{
		case 'minus':
			var td = $(obj).parents('td');
			var value = parseInt(td.find('span').text())-1;
			if(value>0)
				td.find('input').attr('value', value).end().find('span').text(value);
			else
				td.parents('tr').hide();
			
			break;
		case 'plus':
			var td = $(obj).parents('td');
			var value = parseInt(td.find('span').text())+1;
			if(value>0)
				td.find('input').attr('value', value).end().find('span').text(value);
			else
				td.parents('tr').hide();
			
			break;
		case 'delete':
			var td = $(obj).parents('tr').find('td').eq(2);
			td.find('input').attr('value', '0').end().find('span').text('0').end().parents('tr').hide();
			
			break;
	}
}
/**
faq.php
*/
function send_quest_check()
{
	if($('input[@name=name]').attr('value')!="Ваше имя" && $('input[@name=header]').attr('value')!="Тема" && $('input[@name=mail]').attr('value')!="Ваш e-mail" && $('input[@name=quest]').attr('value')!="Текст отзыва")
	{
		$('#quest_form').submit();
	}
	else
		alert("Пожалуйста, заполните все поля!");
}
/**
form.php
*/
//s_order
function checkmail(mamm)
{
	var check = true;
	$('form[@name=quest_form]').find('input:visible').each(
		function() {
			var value = $(this).attr('value');
			var text = $(this).parents('tr').find('td').eq(0).text();
			if(value == '' || value == text)
				check = false;
		}
	).end().find('textarea:visible').each(
		function() {
			var value = $(this).text();
			var text = $(this).parents('tr').find('td').eq(0).text();
			if(value == '' || value == text)
				check = false;	
		}
	);
	if(check == true)
		$('form[@name=quest_form]').submit();
	else
		alert('Не все поля заполнены');
}

/*
 * Droppy 0.1.2
 * (c) 2008 Jason Frame (jason@onehackoranother.com)
 */
$.fn.droppy = function(options) {
    
  options = $.extend({speed: 250}, options || {});
  
  this.each(function() {
    
    var root = this, zIndex = 1000;
    
    function getSubnav(ele) {
      if (ele.nodeName.toLowerCase() == 'li') {
        var subnav = $('> ul', ele);
        return subnav.length ? subnav[0] : null;
      } else {
        return ele;
      }
    }
    
    function getActuator(ele) {
      if (ele.nodeName.toLowerCase() == 'ul') {
        return $(ele).parents('li')[0];
      } else {
        return ele;
      }
    }
    
    function hide() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', false);
      setTimeout(function() {
        if (!$.data(subnav, 'cancelHide')) {
          $(subnav).slideUp(options.speed);
        }
      }, 500);
    }
  
    function show() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', true);
      $(subnav).css({zIndex: zIndex++}).slideDown(options.speed);
      if (this.nodeName.toLowerCase() == 'ul') {
        var li = getActuator(this);
        $(li).addClass('hover');
        $('> a', li).addClass('hover');
      }
    }
    
    $('ul, li', this).hover(show, hide);
    $('li', this).hover(
      function() { $(this).addClass('hover'); $('> a', this).addClass('hover'); },
      function() { $(this).removeClass('hover'); $('> a', this).removeClass('hover'); }
    );
    
  });
  
};

//fxpng
(function($) {
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var base = $('base').attr('href'); // need to use this in case you are using rewriting urls
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').substring(0,1)!='/') ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);
