$(document).ready(function(){
	var files = [".pdf"];
	
	$("a").bind("click", function(e) {
		var link = $(this).attr("href");
		var l_link = link.length;
		var ext = link.substr(l_link-4,4);
		for (var i in files) {
			if (files[i] == ext) {
				$(this).attr("target", "_blank");
				break;
			}
		}
	});

	$("a.dev").bind("mouseenter mouseleave", function(e) {
		$("a.footer_art").toggleClass("hovering");
	});
    /* slimbox */
    jQuery(function($) {
	    $("a[rel^='lightbox']").slimbox({counterText:img_full_txt}, null, function(el) {
		    return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	    });
    });
    /*************************************/
    //убираем рамки вокруг ссылок
   // $('a').focus(function(){$(this).blur()});
    //Установка выбраного шрифта с куков
    if(getCookie('FONT_SIZE')) {
	$('body').addClass(getCookie('FONT_SIZE'));
    }
    if(getCookie('CONTRASTING')) {
	$('body').addClass(getCookie('CONTRASTING'));
    }
    //класы с шрифтами
    var smallFSize = 'smallFSize';
    var largeFSize = 'largeFSize';
    var expires = new Date();
    expires.setTime(expires.getTime() + (1000 * 86400 * 365));
    //контрастность
     $(".contrast").click(function(){
	 $('body').toggleClass('contrasting');
	 if (getCookie('CONTRASTING')) {
	     deleteCookie('CONTRASTING','/');
	 } else {
	     setCookie('CONTRASTING','contrasting',expires,'/');
	 }
     });
    // Сбрасываем размер шрифта
    $(".resetFont").click(function(){
	$('body').removeClass('largeFSize smallFSize');
	deleteCookie('FONT_SIZE','/');
    });
    // Увеличиваем размер шрифта
    $(".increaseFont").click(function(){
	$('body').removeClass(smallFSize).addClass(largeFSize);
	setCookie('FONT_SIZE',largeFSize,expires,'/');
	return false;
    });
    // Уменьшаем размер шрифта
    $(".decreaseFont").click(function(){
	$('body').removeClass(largeFSize).addClass(smallFSize);
	setCookie('FONT_SIZE',smallFSize,expires,'/');
	return false;
    });
    //опросник
    $('p.user_answer').click(function(){
	    $('div.user_answer').hide();
	    $('div.user_answer').slideDown();
	    $('div.answers input').attr('checked', '');
	});
    $('div.answers input').change(function(){
	$('div.user_answer').slideUp();
    });
    $("span.close").click(function(){
	$('div.user_answer').slideUp();
    });
    /************news scroller************/
    newsScroll = setTimeout('scrolNews()',1000);
    height = parseInt(document.getElementById( 'newsWrapper' ).offsetHeight);
	h = parseInt(document.getElementById('newsHolder').offsetHeight);
    speed = 1;
    $("#newsWrapper div.news_item").hover(function(){
		clearTimeout(newsScroll);
    },
    function(){
		newsScroll = setTimeout('scrolNews()',500);
    });
});
/**********news scroller**********/
var newsScroll, height, speed;
function scrolNews() {
    var time = 30;
    var top = $("#newsWrapper").css('top');
    top = parseInt(top) - speed;
    $("#newsWrapper").css('top',top+'px');
    if (top < -(height - 15)) {
		$("#newsWrapper").css('top',h);
    }
    if (top == 0 ) time = 1000;
    newsScroll = setTimeout('scrolNews()', time);
}
/**********send_mail***********/
function sendMail(obj,name,domain) {
    obj.href = 'mailto:'+name+'@'+domain;
}
/**********adding to bookmarks***********/
function addToBookmark(a) {
  title=document.title;
  url=document.location;
  try {
    window.external.AddFavorite(url, title);
  }
  catch (e) {
    try {
      window.sidebar.addPanel(title, url, "");
    }
    catch (e) {
      if (typeof(opera)=="object") {
	a.rel="sidebar";
	a.title=title;
	a.url=url;
	return true;
      }
      else {
	alert('Натисніть Ctrl+D щоб добавити сторінку в закладки');
      }
    }
  }
  return false;
}
/***********VOTING*************/
$(document).ready(function(){
	var fldvls = {};
	var frm = document.active;

		var name =  'active';
		fldvls[name] = {};
		var flds = $('input[type!=checkbox]', frm).get();
		for (var j in flds) {
			fld = flds[j]['name'];
			fldvls[name][fld] = flds[j].value;
			var val = flds[j]['value'];
			$(flds[j]).focus(function(){
				var frm = $(this).parents('form');
				if ($(this).attr('value') == fldvls[$(frm).attr('name')][$(this).attr('name')]) {
					$(this).attr('value', '');
				}
			});
			$(flds[j]).blur(function(){
				if ($(this).attr('value') == '') {
					var frm = $(this).parents('form');
					$(this).attr('value',fldvls[$(frm).attr('name')][$(this).attr('name')]);
				}
			});
		}

	var forms = $('form').get();
	for (var i in forms) {
		var form = forms[i];
		$("a.send_poll", form).bind('click', function(e){
			submitVote(this);
		});
		$("a.send_form", form).bind('click', function(e){
			submitForm(this);
		});
	}
});

function submitVote(a) {
	var form = $(a).parents('form');
	if (form) {
		var files = $("input[type=file]", form).get();
		$(a).hide().after('<img class="waiting" src="images/loading.gif" alt="uploading..." />');
		$.postJSONv($(form).attr('action'), $(form).serialize(), function(data){
			if (data.result != true) {
				$(a).show().next().remove();
			}
			if (data.message != '') {
			} else {
				$(a).show().next().remove();
				$(form).children().hide();
				$("select[name=formtype]", $('form', $(form).parent())).hide();
				$('div.message_sent', $(form).parent()).show();
				document.location.href = "/view.poll_results/";
			}
		});
	}
	return false;
}

/*********************************/
function ajaxFileUpload(field, id, callback)
{
	var form = $(field).parents('form');
	var furl = $(form).get(0).action.replace('submit', 'submitFile');
	var file = field.id;

	$(".waiting")
	.ajaxComplete(function(){
		$(this).prev('a.order, a.send', form).show();
		$(this).remove();
		callback();
	})
	/*.ajaxStart(function(){
		$(this).show();
	})*/;

	$.ajaxFileUpload({
		url: furl,
		secureuri: false,
		fileElementId: file,
		data: {'id':id},
		dataType: 'json',
		complete: function() {
		},
		success: function (data, status) {
//			if(typeof(data.error) != 'undefined') {
//				if(data.error != '') {
//					alert(data.error);
//				} else {
//					alert(data.msg);
//				}
//			}
		},
		error: function (data, status, e) {
//			alert(e);
		}
	})
	return false;
}

function submitForm(a) {
	var form = $(a).parents('form');
		$('input, textarea, select', form).parents('td').removeClass('error');
		$('img.code', form).parents('td').removeClass('error');
	if (form) {
		var files = $("input[type=file]", form).get();
		for (var i in files) {
			var uploaded = $('input[name=uploaded]',form).get(0);
			var fld = files[i];
			uploaded.value += ((uploaded.value != '') ? ', ' : '') + fld.value;
		}
		$(a).hide().after('<img class="waiting" src="images/loading.gif" alt="uploading..." />');
		$.postJSONv($(form).attr('action'), $(form).serialize(), function(data){
			if (data.result != true) {
				$(a).show().next().remove();
				if (data.inc_fields){
					for (var i in data.inc_fields) {
						$('input[name=' + data.inc_fields[i] + '], select[name=' + data.inc_fields[i] + '], textarea[name=' + data.inc_fields[i] + ']', form).parents('td').addClass('error');
					}
				}
				if (data.captcha && data.captcha == true) {
					$('input.code', form).parents('td').addClass("error");
				}
			} else {
				if (files.length > 0 && data.id) {
					for (var i in files) {
						ajaxFileUpload(files[i], data.id, function(){
							$(a).show().next().remove();
							$(form).children().hide();
							$("select[name=formtype]", $('form', $(form).parent())).hide();
							$('div.message_sent', $(form).parent()).show();
						});
					}
				} else {
					$(a).show().next().remove();
					$(form).children().hide();
					$("select[name=formtype]", $('form', $(form).parent())).hide();
					$('div.message_sent', $(form).parent()).show();
				}
			}
		});
	}
	return false;
}

$.postJSONv = function(url, data, callback) {
	$.post(url, data, callback, "json");
};
/*********************************/
var Filter;
function cFilter() {
	this.region = 0;
	this.city = 0;
	this.cities = {};
	this.filterCities = function() {
		setCookie('choosen_region', this.region);
		setCookie('choosen_city', this.city);
		$("div.city_blocks").hide();
		if (this.region == 0 && this.city == 0) {
			$("div.city_blocks").show();
			$('#selectCity > option').show();
			return;
		}
		if (this.city != 0) {
			$('#div_city_'+this.city).show();
			return;
		}
		if (this.region == 0) {
			$('#selectCity > option').show();
		} else {
			$('#selectCity > option').hide();
			for (var i in this.cities[this.regions]) {
                if (this.cities[this.regions][i].region == this.region){
                    $('#div_city_'+this.cities[this.regions][i].id).show();
                
                    $('#cities_li_'+this.cities[this.regions][i].id).show();
                }
			}
			$('#cities_li_0').show();
		}
	}

	this.makeCitiesArray = function(cities) {
		if (!cities) return;
		var city;
		for (var i in cities) {
			city = cities[i];
			if (!this.cities[city.regions]) this.cities[city.regions] = [];
			this.cities[city.regions].push(city);
		}
	}

	this.init = function() {
		var cook_region = getCookie('choosen_region');
		var cook_city = getCookie('choosen_city');
		if (cook_region != null || cook_city != null) {
			if (cook_region != null) {
				this.region = parseInt(cook_region);
				$(document).ready(function(){
					$("option#region_li_"+cook_region).trigger('click')
				});
			}
			if (cook_city != null) {
				this.city = parseInt(cook_city);
				$(document).ready(function(){
					$("option#cities_li_"+cook_city).trigger('click')
				});
			}
		}
	}
}

function setFilter() {
	if (Filter != undefined) {
		if (Filter.region != filterRegion) {
			Filter.city = 0;
			Filter.region = filterRegion;
		} else {
			Filter.city = filterCity;
		}
		Filter.filterCities();
	}
}

var to_look_in = {'ua': 'Переглянути на карті більшого розміру',
				  'ru': 'Просмотреть на карте большего размера'}

function toShowFloatBox(obj) {
	var link = obj;
	var href = $(link).attr('href');
	$.floatbox({
	 fade : true,
	 content : '<iframe width="640" height="480" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' + href + '"></iframe> <a href="' + href + '" style="float: left; width: 400px; margin-top: 7px;">' + to_look_in[language] + '</a>'
	});
 return false;
 }
