/*** Placeholder Script ***/
jQuery.fn.extend({
    placeHolder : function() {
		this.focus(function(){
			if (jQuery(this).attr("value") == jQuery(this).attr("title")){
				jQuery(this).attr("value", "")
			}
		});
		this.blur(function(){
			if (jQuery(this).attr("value") == ""){
				jQuery(this).attr("value", jQuery(this).attr("title"));
			}
		});
    }
});

$(document).ready(function(){

//плейсхолдер


$("#p_f_1_23").placeHolder();

//сохранение параметров у ссылок
if(window.location.href.indexOf('?') != -1){

	urlFilter = window.location.href.split('?')[1];
	urlGetStr = urlFilter.split('&');
	$(".filter-item a").each(function(){
		curLinkUrl = $(this).attr('href');
		for(i = 0; i < urlGetStr.length; i++){
			el = urlGetStr[i].split('=');
			if(curLinkUrl.indexOf(el[0]) == -1){
				if($(this).hasClass('last') && el[0] == 'p_f_1_119_hi'){
				} else {
					curLinkUrl += '&' + el[0] + '=' + el[1];
				}	
				//alert(curLinkUrl);
			}
		}
		$(this).attr('href', curLinkUrl);
	});
}

//Показ системных сообщений
function showMessage(mesText, titleDialog){
	$("#wrapper").prepend('<div id="mesCont">' + mesText + '</div>');
	
	if ($.browser.msie && $.browser.version == 6) $("select").show();
	$("#mesCont").dialog({
					bgiframe: true,
					modal: true,
					draggable: true,
					resizable: false,
					title: titleDialog,
					width:450,
					zIndex: 9999,
					dialogClass: 'toLeft',
					buttons: {
							'Закрыть': function() {
							$(this).dialog('close');
							$(this).dialog("destroy");
							if ($.browser.msie && $.browser.version == 6) $("select").show();
						}
					}
	});
}
function str_replace(search, replace, subject) {
	return subject.split(search).join(replace);
}

//вывод формы регистрации
//328
$("#regLink").colorbox({iframe:true, width:435, height:"100%", opacity:0.8, overlayClose:false});
$("#changeLink").colorbox({iframe:true, width:435, height:"100%", opacity:0.8, overlayClose:false});

flag = $("#autoOpen");
if(flag.length > 0){
	$("a#autoOpen").colorbox({iframe:true, width:435, height:"100%", opacity:0.8, open:true, overlayClose:false});
}

//
$(".compare-item").mouseover(function(){
	$(this).addClass('compare-hover');
	flag = $(this).find('.del-link');
	if(flag.length == 0){
		$(this).find('.del-link').remove();
		$(this).prepend('<a href="' + $(this).find('.compare-link').attr('href') + '" class="del-link" title="Убрать из избранного">x</a>');
	}
});
$(".compare-item").mouseleave(function(){
	$(this).removeClass('compare-hover');
	//$('.del-link').remove();
});


//compare-link
$(".compare-link").unbind('click').click(function(){
	url = $(this).attr('href');
	elLink = $(this);
	$.get(url, {},
		function(data){
		
			if(url.indexOf('=1') != -1){ //добавление
				elLink.addClass('delete');
				elLink.html('убрать из избранного');
				url = str_replace('=1', '=0', url);
				elLink.attr('href', url);
				
				
			} else { //удаление из избранного
				elLink.removeClass('delete');
				elLink.html('добавить в избранное');
				url = str_replace('=0', '=1', url);
				elLink.attr('href', url);
				
				
			}
			
				$.get('/compare.php', {},
					function(data){

						$(".login-link p:eq(1) a").html(data);
					}, "text"
				);
			
		}, "text"
	);
	
		
	return false;
});
$(".compare-item .compare-link").unbind('click');


//переключение фильтра
$("#dopFileds").click(function(){
	$("#dopFildsBlock").toggle();

	return false;
});
//сортировка
$("#s_f_1").change(function(){
	cUrl = window.location.href;
	nUrl = cUrl;
	if(cUrl.indexOf('?') == '-1'){
		nUrl += '?s_f_1=' + $("#s_f_1").val();
	} else {
		nUrl += '&s_f_1=' + $("#s_f_1").val();
	}
	window.location.href = nUrl;
});


//Разное
$(".news-blog-item:last").addClass('no-border');



//вывод всех направлений
$(".allItem").click(function(){
	state = $(this).attr('rev');
	curTitle = $(this).html();
	newTitle = $(this).attr('rel');
	
	switch (state){
		case '0': {
			$(this).parent().parent().find('li.hide').show(500);
			$(this).html(newTitle);
			$(this).attr('rel', curTitle);
			$(this).attr('rev', '1');
			break;
		}
		case '1': {
			$(this).parent().parent().find('li.hide').hide(500);
			$(this).html(newTitle);
			$(this).attr('rel', curTitle);
			$(this).attr('rev', '0');
			break;
		}
		
	}
	

	
	return false;
});

//выпадающее меню
$("#menu ul li, #menu-type2 ul li").mouseover(function(){
	$("#menu ul li, #menu-type2 ul li").find("ul").hide();
	$("#menu ul li, #menu-type2 ul li").removeClass("activeS");
	
	$(this).find("ul").show();
	$(this).addClass("activeS");
});
$(".page, #header, #header-small, #middle").mouseover(function(){
	$("#menu ul li, #menu-type2 ul li").find("ul").hide();
	$("#menu ul li, #menu-type2 ul li").removeClass("activeS");
});

//Плеер
$(".player").each(function(i){
	$(this).attr('id', 'el_' + i);
	$(this).prepend('<span class="button"></span>');
	
	fileToPlay = $(this).attr('href'); 
		flowplayer("el_" + i, "/flash/flowplayer.swf", {
			plugins: {
				controls: {
					url: '/flash/flowplayer.controls.swf', 
					slowForward: false, 
					mute: false, 
					time:false
				}, 
				pseudo: { 
					url: '/flash/flowplayer.pseudostreaming-3.2.2.swf' 
				}
				
			},
			clip: {
				autoPlay: true, 
				autoBuffering: true, 
				scaling: 'scale'
			}, 
			playlist: [				// an array of Clip objects
						{
							autoPlay: true, 
							autoBuffering: true,
							//start: 162,
							provider: 'pseudo', 
							url: fileToPlay
						}
			]
		});
});



//скроллер на главной
bannerFlag = $("#scrollHeader");
if(bannerFlag.length > 0){
		$('#scrollHeader').cycle({ 
		fx:      'fade', 
		speed:    1000, 
		timeout:  10000, 
		pager: '#headMenu', 
		pause: 1, 
		activePagerClass: 'active', 
		pagerAnchorBuilder: function(idx, slide) { 
			return '#headMenu li:eq(' + idx + ')'; 
		}
	});
}
//скроллер в карточке товара
bannerFlag = $("#objectSlider");
if(bannerFlag.length > 0){
		$('#objectSlider').cycle({ 
		fx:      'scrollVert', 
		speed:    1000, 
		timeout:  10000, 
		pager: '#headMenu', 
		pause: 1, 
		activePagerClass: 'active' 
	});
	
	$('#objectSlider').cycle('pause'); //ставим на паузу
	$("#toTop").click(function(){ //предыдущий слайд
		$('#objectSlider').cycle('prev');
		
		return false;
	});
	$("#toBottom").click(function(){ //следующий слайд
		$('#objectSlider').cycle('next');
		
		return false;
	});
}

//форма обратной связи
contactFlag = $("#contactCont");
if(contactFlag.length > 0){
	function contactInit(){
		$('#contactForm').submit(function(){
			return false;
		});
		
		$('#submitC').click(function(){
			$('#user_f_1').css('border-color', '#C0BBAD');
			$('#user_f_3').css('border-color', '#C0BBAD');
			
			if($('#user_f_1').val() == '' || $('#user_f_1').val() == 'Ваше сообщение'){
				$('#user_f_1').css('border-color', '#FF0000');
				showMessage('Укажите текст сообщения', 'Ошибка');
				return false;
			}
			if($('#user_f_3').val() == '' || $('#user_f_3').val() == 'Ваша контактная информация'){
				$('#user_f_3').css('border-color', '#FF0000');
				showMessage('Укажите контактную информацию', 'Ошибка');
				return false;
			}
			var options = {
			target: "#contactCont",
			url: "/order.php",
			type: "POST", 
			success: function() {
				 contactInit();
			}
			};
			$("#contactForm").ajaxSubmit(options);
			
			return false
		});
	}
	
	$("#contactCont").load('/order.php', function(){
		contactInit();
	});
}

//Версия для печати
function  strip_tags(str, allowed_tags) {
            var key = '', allowed = false;
            var matches = [];
            var allowed_array = [];
            var allowed_tag = '';
            var i = 0;
            var k = '';
            var html = '';
 
            var replacer = function(search, replace, str) {
                return str.split(search).join(replace);
            };
 
            // Build allowes tags associative array
            if (allowed_tags) {
                allowed_array = allowed_tags.match(/([a-zA-Z1-6]+)/gi);
            }
 
            str += '';
 
            // Match tags
            matches = str.match(/(<\/?[\S][^>]*>)/gi);
 
            // Go through all HTML tags
            for (key in matches) {
                if (isNaN(key)) {
                    // IE7 Hack
                    continue;
                }
 
                // Save HTML tag
                html = matches[key].toString();
 
                // Is tag not in allowed list? Remove from str!
                allowed = false;
 
                // Go through all allowed tags
                for (k in allowed_array) {
                    // Init
                    allowed_tag = allowed_array[k];
                    i = -1;
 
                    if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
                    if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
                    if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
                    // Determine
                    if (i == 0) {
                        allowed = true;
                        break;
                    }
                }
 
                if (!allowed) {
                    str = replacer(html, "", str); // Custom replace. No regexing
                }
            }
 
            return str;
        }

$("#print2").click(function() {
	url = $(this).attr('rel');
	var win = open(url, "print_window", "width=1000,height="+ (screen.availHeight-70) +",left="+((screen.availWidth-1000) / 2)+",top=0,status=no,toolbar=no,menubar=yes,location=no,resizable=yes, scrollbars=yes");
	win.focus();
	win.document.close();
	return false
});
		
$("#print").click(function() {
	cont_1 = $("div.description").html();
	cont_2 = $("div.map").html();
	
	mapHtml = '';
	mapLink = $("a[rel='shadowbox']").attr('id');
	
	
	$("#wrapper").prepend('<div style="display:none" id="forMap"></div>');
	
	

		cont_1 = strip_tags(cont_1, '<h1>, <table>, <tr>, <td>, <th>, <div>, <p>, <h2>, <h3>, <h4>, <b>, <strong>, <i>, <em>, <ul>, <li>, <ol>, <br>, <hr>, <img>');
		cont_2 = strip_tags(cont_2, '<h1>, <table>, <tr>, <td>, <th>, <div>, <p>, <h2>, <h3>, <h4>, <b>, <strong>, <i>, <em>, <ul>, <li>, <ol>, <br>, <hr>, <img>');
	
	var curTitle = $("div.text_2").find("h2:first").text();
	
	var win = open("/sys/print.php", "print_window", "width=900,height="+ (screen.availHeight-70) +",left="+((screen.availWidth-1000) / 2)+",top=0,status=no,toolbar=no,menubar=yes,location=no,resizable=yes, scrollbars=yes");
	win.focus();
	win.document.write("<html><head>");	
	win.document.write('<link rel="stylesheet" href="/css/style.css" type="text/css">');
	win.document.write('<link rel="stylesheet" href="/css/print.css" type="text/css">');
	
	win.document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>');
	win.document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>');
	
	/*win.document.write('<script type="text/javascript" src="http://api-maps.yandex.ru/1.1/index.xml?key=AFi8PEwBAAAA6eEAUQQAKiAxJQKiVzdWGCnfAQy4VfnGul8AAAAAAAAAAACIrmRQZxhgnVcr-uzwxzUjHa93iw=="></script>');
	win.document.write('<link href="http://api-maps.yandex.ru/1.1.15/_YMaps.css" rel="stylesheet">');
	win.document.write('<script src="http://api-maps.yandex.ru/1.1.15/_YMaps.js" charset="utf-8" type="text/javascript"></script>');
	win.document.write('<script src="http://api-maps.yandex.ru/1.1.15/xml/data.xml?v=1.49.3" charset="utf-8" type="text/javascript"></script>');*/
	//win.document.write('');
	
	
	
	
	
    

	
	win.document.write('<!--[if IE]><style type="text/css"> @import "/css/ie.css"; </style><![endif]--><!--[if lte IE 6]><style type="text/css"> @import "/css/ie6.css"; </style><![endif]-->');
	win.document.write('<style>body{padding:10px 15px; color:#000} h2{margin-top:15px} td{font-size:12px; color:#000} .detList li{color:#000} h1{font-size:42px; margin-top:20px; line-height:42px; color:#000} .noPrint{display:none}</style>');
	//win.document.write("<title>" + curTitle + "</title></head><body onLoad=\"$('#ymapCont').load(\'" + mapLink + "\')\">");
	
	win.document.write('<div id="printf"><a href="#">Распечатать</a></div><div class="clear"></div>');
	win.document.write('<h1>' + curTitle + '</h1>');
	win.document.write('<h2>Описание</h2>');
	win.document.write('<div class="description">' + cont_1 + '</div>');
	win.document.write('<h2>Дополнительная информация</h2>');
	win.document.write('<div class="map">' + cont_2 + '</div>');


	win.document.write('<script>document.getElementById("printf").onclick = function(){window.print(); return false;}</script>');
	win.document.write("</body></html>");
	if (navigator.userAgent.indexOf('Chrome') > 0) win.location.href="#";
	

	
	
	
	win.document.close();
	
	return false;
});

//Загрузка кол-ва просмотров
countFlag = $("#currentUrl");
if(countFlag.length > 0){
	currentUrlV = $("#currentUrl").val();
	$("#count").load('http://www.sohoestate.ru/count.php?query=' + currentUrlV);
//$("#count").html('1');
}
	
});
