// JavaScript Document

$(document).ready(function(){
    $(document).pngFix();

    $("div.cphoto").hover(function(){
        //alert("ntcn");
        $(this).next("div.pcomment").css("left", $(this).parents("td").offset().left)
        .css("top", $(this).parents("td").offset().top+170)
        .css("display", "block").animate({opacity:"0.8"}, "fast");
    },function(){
        $(this).next("div.pcomment").css("display", "none").animate({opacity:"0"}, "fast");
    });


    for( a = 2; a <= 5; a++){
        $("table#ph"+a+" tr.prow:gt(0)").css("display", "none");
    }

    $('body').bind('mouseup',function(event){
        sel = getsel();
        if( sel ){
            pos = mousePageXY(event);
            $('#error_but').css('left',pos[0]+'px').css('top',pos[1]+'px').show();
            $('#selected_text').html(sel);
            $('#selected_text_input').attr('value', sel);
        }
    });

    $('body').bind('mouseup', function(){
        if( !sel ){
            if($('#error_but').css('display') == 'block') $('#error_but').hide();
        }
    });

    /*$('table.block div.head').click(function(){
        $(this).next('div.block_cont').slideToggle('fast');
    });*/

});

function mousePageXY(e)
{
  var x = 0, y = 0;

  if (!e) e = window.event;

  if (e.pageX || e.pageY)
  {
    x = e.pageX;
    y = e.pageY;
  }
  else if (e.clientX || e.clientY)
  {
    x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
    y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
  }

  return [x, y];
}

function getsel(){

    selObj = window.getSelection();

    return selObj.toString();

}

function send_error_report(id_company, company_name){
    $('#error_but').hide();

    $('#company_name').html(company_name);
    $('#idcompany_error_report').attr('value', id_company);

    $('#error_report_div').dialog('open');
}

function send_user_info(id){
    $.ajax({
        url:'/phpajax/sendmail.php?id='+id,
        success:function(){ $('div#err').html('Информация отправлена!'); }
    });
}

function getBodyScroll(){
    topScroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
    leftScroll = self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);

    return [topScroll, leftScroll];
}

function getPageSize(){
    height = document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
    width = document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;

    return [width, height];
}

function view_tr(num){
    $(".slideUp").hide();
    $(".slideDown").show();
    $("#slideDown"+num).hide();
    $("#slideUp"+num).show();
    for( a = 1; a <= 5; a++){
        $("table#ph"+a+" tr.prow:gt(0)").css("display", "none");
    }
    $("table#ph"+num+" tr.prow:gt(0)").show();
}
function hide_tr(num){
    $("#slideDown"+num).show();
    $("#slideUp"+num).hide();
    $("table#ph"+num+" tr.prow:gt(0)").hide();
}

function set_count(itm){
    var count = document.getElementById(itm).value;
    count++;
    return count;
}

function del_service(id, p, order, sort_, status){
    if( confirm("Удалить услугу?") )
        $("#slist").load('/phpajax/delservice.php?id='+id+'&p='+p+'&order='+order+'&sort='+sort_+'&status='+status);
}

function del_in_tarif(id, idtarif){
    if( confirm('Удалить услугу?') ){
        //alert('../phpajax/delintarif.php?id='+id+'&idtarif='+idtarif);
        $("#slist").load('/phpajax/delintarif.php?id='+id+'&idtarif='+idtarif);
    }
}

function del_tarif(id, p, order, sort_, status){
    if( confirm('Удалить тариф?') )
        $("#tlist").load('/phpajax/deltarif.php?id='+id+'&p='+p+'&order='+order+'&sort='+sort_+'&status='+status);
}

function ask(url){
    if( confirm('Вы уверены?') )
        location.href=url;
}

function add_phone(num){
    /*
    document.getElementById('phones').innerHTML += '<table class="editlist"><tr><td class="label">Телефон '+num+'</td><td><input type="hidden" name="idphone'+num+'" value="0"><input class="text" type="text" name="phone'+num+'" value="" maxlength="24"/></td><td class="label">Тип телефона</td><td><select name="type'+num+'"><option value="1">Стационарный</option><option value="2">Сотовый</option><option value="3">Факс</option></select></td></tr><tr><td class="label">Комментарий</td><td colspan="3"><input class="text" type="text" name="pcomment'+num+'" value="" maxlength="255"/></td></tr></table>';
    document.getElementById('countphone').value = num;
    */
    $('#phones').append('<table class="editlist"><tr><td class="label">Телефон '+num+'</td><td><input type="hidden" name="idphone'+num+'" value="0"><input class="text" type="text" name="phone'+num+'" value="" maxlength="24"/></td><td class="label">Тип телефона</td><td><select name="type'+num+'"><option value="1">Стационарный</option><option value="2">Сотовый</option><option value="3">Факс</option></select></td></tr><tr><td class="label">Комментарий</td><td colspan="3"><input class="text" type="text" name="pcomment'+num+'" value="" maxlength="255"/></td></tr></table>');
    $('#countphone').attr('value', num);
}

function add_mail(num){
    /*
    document.getElementById('emails').innerHTML += '<table class="editlist"><tr><td class="label">E-mail '+num+'</td><td><input type="hidden" name="idemail'+num+'" value="0"><input class="text" type="text" name="email'+num+'" value="" maxlength="64"/></td><td class="label">Комментарий</td><td><input class="text" type="text" name="ecomment'+num+'" value="" maxlength="255"/></td></tr></table>';
    document.getElementById('countmail').value = num;
    */

    $('#emails').append('<table class="editlist"><tr><td class="label">E-mail '+num+'</td><td><input type="hidden" name="idemail'+num+'" value="0"><input class="text" type="text" name="email'+num+'" value="" maxlength="64"/></td><td class="label">Комментарий</td><td><input class="text" type="text" name="ecomment'+num+'" value="" maxlength="255"/></td></tr></table>');
    $('#countmail').attr('value', num);
}

function show_hide_areas(){
	$('#area').css({display : ($('#clist').val() == 1) ? '' : 'none'});

	/*if(document.getElementById('clist').value == 1){
        document.getElementById('area').style.display = '';
    }else{
        document.getElementById('area').style.display = 'none';
    }*/

}

function newsup(id){
	$.getJSON('/phpajax/newsup.php?id='+id, function(r){
		if(r.error){
			alert(r.error);
		}
		else if(r.newdate){
			$('.news_' + id + ' span.date-container').text(r.newdate).fadeOut(50).fadeIn(50).fadeOut(50).fadeIn(50).fadeOut(50).fadeIn(50);
		}
	});
}

function vacup(id){
	$.getJSON('/phpajax/vacup.php?id='+id, function(r){
		if(r.error){
			alert(r.error);
		}
		else if(r.newdate){
			$('.vac_' + id + ' span.date-container').text(r.newdate).fadeOut(50).fadeIn(50).fadeOut(50).fadeIn(50).fadeOut(50).fadeIn(50);
		}
	});
}

function unrealized(){
    alert('Не работает!\nОграничения демо версии :)');
}

function check_rub_count(num, el){
    a = 0;
    $(".rub_check:checked").each(function(){
        a++;
    });

    if( num < a ){
        alert('Подключено максимально возможное количество рубрик! (Доступно: '+num+')');
        //el.click();
        el.checked = false;

    }
}

/*
========= ФУНКЦИЯ ПРОВЕРКИ ПОЛЕЙ ФОРМЫ =========

fields - двумерный массив с id полей и человеческим названием для юзверей
Пример:
var fields = [
    ["id1", "Поле 1"],
    ["id2", "Поле 2"]
];
fields[1][1] будет иметь значение "Поле 2".
*/
function check_fields(fields){
    ok = true;
    len = fields.length;

    if(len > 0){
        a = 0;
        empty = new Array();
        for(n = 0; n < len; n++){
            if(document.getElementById(fields[n][0]) && document.getElementById(fields[n][0]).value == ''){
                ok = false;
                empty[a] = fields[n][1];
                a++;
            }
        }

        emptylen = empty.length;
        if(emptylen > 0){
            list ="";
            for(b = 0; b < emptylen; b++){
                list += '\t-  " ' + empty[b] + ' "\n\n';
            }
            alert('Заполните следующие поля:\n\n'+list);
        }
        return ok;
    }else{
        alert("Не заданы поля для проверки!");
        return false;
    }

}

function subcat(id){
    $("#catdiv").load('/phpajax/subcat.php?id='+id);
}

/*====================================================*/

function vote(idtheme){
    //alert("../phpajax/vote.php?act=vote&idtheme="+idtheme+"&idoption="+$("input.vote:checked").attr("value"));
    $("#votebody").load("/phpajax/vote.php?act=vote&idtheme="+idtheme+"&idoption="+$("input.vote:checked").attr("value"));
}

function vote_page(idtheme){
    //alert("../phpajax/votepage.php?act=vote&idtheme="+idtheme+"&idoption="+$("input.vote:checked").attr("value"));
    $("#votebody").load("/phpajax/votepage.php?act=vote&idtheme="+idtheme+"&idoption="+$("input.vote:checked").attr("value"));
}

function cat_stat_tbl(idhead, month, year){
    $("#rview").load("/phpajax/catstat.php?id="+idhead+"&month="+month+"&year="+year);
}

var sbmt = true;

function check_field(itm){
    if(document.getElementById(itm) && document.getElementById(itm).value == '') sbmt = false;
}

function check_all_fields(max_rub){
    return_ = true;
    sbmt = true;
    check_field('name');
    check_field('ctype');
    check_field('clist');
    if(sbmt == true){
        return_ = true;
    }else{
        alert('Заполните все необходимые поля!');
        return_ = false;
    }

    name = $("#name").attr("value");
    jname = $("#jname").attr("value");

    $.getJSON("/phpajax/checkcomp.php?name="+name+"&jname="+jname,
    function(data){
        if(data.exist == 0){
            return_ = false;
            alert(data.exist+'Компания с таким названием уже существует. Воспользуйте поиском еще раз. Если все данные верны, попробуйте ввести название по-другому!');
        }
    });

    a = 0;
    $(".rub_check:checked").each(function(){
        a++;
    });

    if( max_rub < a ){
        return_ = false;
        el.click();
        alert('Подключено максимально возможное количество рубрик! (Доступно: '+num+')');
    }

    if( a == 0 ){
        return_ = false;
        alert('Выберете рубрику!');
    }

    return return_;
}

function check_new_cat_name(){
    sbmt = true;
    check_field('newcatname');
    if(sbmt == true){
        return true;
    }else{
        alert('Введите имя новой категории!');
        return false;
    }
}

function check_cat_name(){
    sbmt = true;
    check_field('edtcatname');
    if(sbmt == true){
        return true;
    }else{
        alert('Введите новое имя категории!');
        return false;
    }
}

function check_user_fields(){
    sbmt = true;
    check_field('lgn');
    check_field('psswrd');
    check_field('psswrdconf');
    if(sbmt == true){
        return true;
    }else{
        alert('Заполните все необходимые поля!');
        return false;
    }
}

function check_reg_fields(){
    sbmt = true;
    check_field('lgn');
    check_field('pswdreg');
    check_field('pswdreg1');
    check_field('username');
    check_field('email');

    if(document.getElementById('rules').checked == false) sbmt = false;

    if(sbmt == true){
        return true;
    }else{
        alert('Заполните все необходимые поля!');
        return false;
    }
}

function check_photo_fields(){
    sbmt = true;
    check_field('photo');
    if(sbmt == true){
        return true;
    }else{
        alert('Заполните все необходимые поля!');
        return false;
    }
}

function check_file_fields(){
    sbmt = true;
    check_field('file');
    check_field('filename');
    if(sbmt == true){
        return true;
    }else{
        alert('Заполните все необходимые поля!');
        return false;
    }
}

function check_file_edit_fields(){
    sbmt = true;
    check_field('efnf');
    if(sbmt == true){
        return true;
    }else{
        alert('Заполните все необходимые поля!');
        return false;
    }
}

function check_news_fields(){
    sbmt = true;
    check_field('header');
    check_field('textnews');
    if(sbmt == true){
        return true;
    }else{
        alert('Заполните все необходимые поля!');
        return false;
    }
}

function check_vac_fields(){
    sbmt = true;
    check_field('header');
    check_field('vacdesc');
    if(sbmt == true){
        return true;
    }else{
        alert('Заполните все необходимые поля!');
        return false;
    }
}

function show_add_cat_form(){
    document.getElementById('addcatform').style.display='block';
}

function show_edt_cat_form(){
    $('#edtcatform').show();
}

function show_move_cat_form(){
   	$('#movecatform').show();
    var id = $('#movecatform input[name="idcat"]').val();
	if($('#movecatform select option').length < 2){
		$('#movecatform select').load("/phpajax/getcategorytree.php", {'id': id});
	}
}

function show_edt_photo_form(idphoto, comment){
    document.getElementById('editphotocomment').style.display='block';
    document.getElementById('ideditphoto').value = idphoto;
    document.getElementById('epcf').value = comment;
}

function hide_edt_photo_form(){
    document.getElementById('editphotocomment').style.display='none';
    document.getElementById('ideditphoto').value = '';
    document.getElementById('epcf').value = '';
}

function show_edt_file_form(idfile, name, comment){
    //alert(idfile+', '+name+', '+comment);
    document.getElementById('editfileform').style.display='block';
    document.getElementById('ideditfile').value = idfile;
    document.getElementById('efnf').value = name;
    document.getElementById('efcf').value = comment;
}

function hide_edt_file_form(){
    document.getElementById('editfileform').style.display='none';
    document.getElementById('ideditfile').value = '';
    document.getElementById('efnf').value = '';
    document.getElementById('efcf').value = '';
}

function conf_del(url, text){
    if(confirm(text)){
        location.href=url;
    }
}

function conf_del_photo(id, text){
    if(confirm(text)){
        $.get('/phpajax/delphoto.php?id=' + id, function(data){$('#img' + id + ', ' + '#imgedt' + id).text(data);});
    }
}

function set_active(idlogo, id){
    location.href='/sql.php?act=setact&idlogo='+idlogo+'&id='+id;
}

function unset_active(idlogo, id){
    location.href='/sql.php?act=unsetact&idlogo='+idlogo+'&id='+id;
}

function set_photo_priority(idphoto, type, id){
    location.href='/sql.php?act=setpriority&idphoto='+idphoto+'&type='+type+'&id='+id;
}

function unset_photo_priority(idphoto, type, id){
    location.href='/sql.php?act=unsetpriority&idphoto='+idphoto+'&type='+type+'&id='+id;
}

function show_div(e){
    document.getElementById('err').innerHTML = 'Слой Слой Слой Слой Слой Слой';
    document.getElementById('err').style.left = e.clientX + "px";
    document.getElementById('err').style.top = e.clientY + "px";
    document.getElementById('err').style.display = 'block';

}

function coor(e){
    alert(navigator.appName);
}

function vote_delete(id, p, order, sort_){
    if( confirm('Удалить опрос?') ){
        $("#vote").load('/phpajax/delvote.php?id='+id+'&p='+p+'&order='+order+'&sort='+sort_);
    }
}

function add_service(service, count, period){
    //alert('Вы уверены, что хотите подключить '+service+' в количестве '+count+' на период '+period+' дней именно этой компании?');
    if( confirm('Вы уверены, что хотите подключить "'+service+'" в количестве '+count+' на период '+period+' дней именно этой компании?') ){
        if( confirm('Точно?') ) return true;
        else return false;
    }else return false;
}

function del_comp_service(id){
    if( confirm('Удалить подключенную услугу?') ){
        $.ajax({
            url:'/phpajax/delcompservice.php?id='+id,
            beforeSend: function(){
                $('body').append('<div id="bgflow"></div>');
                $('body').append('<div id="loading"><img src="/images/loading.gif" /></div>');

                bodyScroll = getBodyScroll();
                pageSize = getPageSize();

                $('#bgflow').css("height", pageSize[1]).css("top", bodyScroll[0]).css({opacity: "0"}).css("display", "block").animate({opacity: "0.3"}, "fast");
                $('#loading').css("top", pageSize[1]/2-16).css("left", pageSize[0]/2-16).fadeIn("fast");
            },
            success: function(data){
                $('#bgflow').remove();
                $('#loading').remove();
                $('#result').html(data);

                $('#compserv tr#'+id).remove();
            }
        });
    }
}

function toggle_comp(id){
    $.ajax({
        url:'/phpajax/toggle_comp.php?id='+id,
        beforeSend: function(){
            $('body').append('<div id="bgflow"></div>');

                bodyScroll = getBodyScroll();
                pageSize = getPageSize();

                $('#bgflow').css("height", pageSize[1]).css("top", bodyScroll[0]).css({opacity: "0"}).css("display", "block").animate({opacity: "0.7"}, "fast");
        },
        success: function(data){
            $("#bgflow").remove();
            $("#err").remove();
            $("#msg").remove();

            if( $("#view_"+id).attr("src") == '/images/i_show.gif' )
                $("#view_"+id).attr("src", '/images/i_hide.gif');
            else if( $("#view_"+id).attr("src") == '/images/i_hide.gif' )
                $("#view_"+id).attr("src", '/images/i_show.gif');
        }
    });
}

//------- AJAX -------

var element;

function onchange_city_type(){
    element='city';
    send_request('phpajax/getcitys.php?type='+document.getElementById('ctype').value);
    // //document.getElementById('stype').innerHTML = "<option value="">- Не определено -</option>";
    // //document.getElementById('slist').innerHTML = "<option value="">- Не определено -</option>";
}

function onchange_city(){
    element='strtype';
    send_request('/phpajax/getstreettypes.php?idcity='+document.getElementById('clist').value);
    //document.getElementById('slist').innerHTML = "<option value="">- Не определено -</option>";
}

function onchange_street_type(){
    element='street';
    //document.write(document.getElementById('stype').value);
    send_request('/phpajax/getstreets.php?idcity='+document.getElementById('clist').value+'&idtype='+document.getElementById('stype').value);
}

function delete_phone(idphone, idcompany){
    if(confirm('Вы действительно хотите удалить телефон?')){
        element='phones';
        send_request('/phpajax/delphone.php?idphone='+idphone+'&idcomp='+idcompany);
    }
}

function delete_email(idemail, idcompany){
    if(confirm('Вы действительно хотите удалить e-mail?')){
        element='emails';
        send_request('/phpajax/delemail.php?idemail='+idemail+'&idcomp='+idcompany);
    }
}

function show_branches(id){
    element='brnchs';
    send_request('/phpajax/showbranch.php?id='+id);
}

function hide_branches(id){
    element='brnchs';
    send_request('/phpajax/hidebranch.php?id='+id);
}

function choose_cat(id){
    document.getElementById('category').style.display='none';
    element='choose_category';
    send_request('/phpajax/chscategory.php?id='+id);
}

function confirm_cat(id){
    document.getElementById('category').innerHTML = '';
    document.getElementById('category').style.display='block';
    document.getElementById('choose_category').style.display='none';
    document.getElementById('idcategory').value = id;
    element='category';
    send_request('/phpajax/confcategory.php?id='+id);
}

function check_login(login){
    element = 'checkres';
    send_request('/phpajax/checklogin.php?login='+login);
}

function get_bus(st1, st2){
    element = 'busno';
    send_request('/phpajax/getbus.php?st1='+st1+'&st2='+st2);
}

function st_in_route(idst1, idst2, idbus){
    element = 'stlist';
    send_request('/phpajax/stinroute.php?idst1='+idst1+'&idst2='+idst2+'&idbus='+idbus);
}

var request = false;
function create_request(){
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
        try {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (failed) {
            request = false;
        }
        }
    }
    if (!request) alert("Error XMLHttpRequest");
}

/*function send_request(url){
    if (url != ''){
        create_request();
        //var fullurl = url+id;
        request.open("GET",url,true);
        request.onreadystatechange = update_page;
        request.send(null);
    }
}*/

function send_request(url){
    if (url != '') $.get(url, update_page);
}

/*function update_page(){
    if (request.readyState == 4){
        if (request.status == 200){
            var resp = request.responseText;
            document.getElementById(element).innerHTML = '';
            document.getElementById(element).innerHTML = request.responseText;

            if(element == 'city'){
                document.getElementById('stype').innerHTML = '<option value="">- Не определено -</option>';
                document.getElementById('slist').innerHTML = '<option value="">- Не определено -</option>';
            }

            if(element == 'strtype'){
                document.getElementById('slist').innerHTML = '<option value="">- Не определено -</option>';
            }
        }
    }
}*/

function update_page(data){
	$('#' + element).html(data);
	if(element == 'city'){
		$('#stype').html('<option value="">- Не определено -</option>');
		$('#slist').html('<option value="">- Не определено -</option>');
	}
	if(element == 'strtype'){
		$('#slist').html('<option value="">- Не определено -</option>');
	}
}

/*function request_del_photo(url){
    if (url.length) $.get(url, function(data){ $('#img' + idphoto + ', ' + '#imgedt' + idphoto).text(data); });
}*/

/*function update_page_del_photo(){
    if (request.readyState == 4){
        if (request.status == 200){
            var resp = request.responseText;
            document.getElementById('img'+idphoto).innerHTML = request.responseText;
            document.getElementById('imgedt'+idphoto).innerHTML = request.responseText
        }
    }
}*/











var ns6=document.getElementById&&!document.all

function restrictinput(maxlength,e,placeholder){
    if (window.event&&event.srcElement.value.length>=maxlength)
        return false
    else if (e.target&&e.target==eval(placeholder) && e.target.value.length>=maxlength){
        var pressedkey=/[a-zA-Z0-9\.\,\/]/
        if (pressedkey.test(String.fromCharCode(e.which)))
            e.stopPropagation()
    }
}

function countlimit(maxlength,e,placeholder){
    var theform=eval(placeholder)
    var lengthleft=maxlength-theform.value.length
    var placeholderobj=document.all? document.all[placeholder] :
    document.getElementById(placeholder)
    if (window.event||e.target&&e.target==eval(placeholder)){
        if (lengthleft<0)
            theform.value=theform.value.substring(0,maxlength)
        placeholderobj.innerHTML=lengthleft
    }
}

function displaylimit(theform,thelimit){
    //var limit_text='Еще <b><span id="'+theform.toString()+'">'+thelimit+'</span></b> символов разрешено ввести в форму '
    var limit_text = "<small>Осталось <b><span id=\""+theform.toString()+"\">"+thelimit+"</span></b> символов</small>";
    if (document.all||ns6){
        $("#char_count").html('');
        $("#char_count").html(limit_text);
        //document.write(limit_text);
    }
    if (document.all){
        eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
        eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
    }
    else if (ns6){
        document.body.addEventListener('keypress', function(event){ restrictinput(thelimit,event,theform) }, true);
        document.body.addEventListener('keyup', function(event){ countlimit(thelimit,event,theform) }, true);
    }
}

function displaylimit_1(theform,thelimit){
    //var limit_text='Еще <b><span id="'+theform.toString()+'">'+thelimit+'</span></b> символов разрешено ввести в форму '
    var limit_text = "<small>Осталось <b><span id=\""+theform.toString()+"\">"+thelimit+"</span></b> символов</small>";
    if (document.all||ns6){
        $("#char_count1").html('');
        $("#char_count1").html(limit_text);
        //document.write(limit_text);
    }
    if (document.all){
        eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
        eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
    }
    else if (ns6){
        document.body.addEventListener('keypress', function(event){ restrictinput(thelimit,event,theform) }, true);
        document.body.addEventListener('keyup', function(event){ countlimit(thelimit,event,theform) }, true);
    }
}


/*
 * FancyBox - simple jQuery plugin for fancy image zooming
 * Examples and documentation at: http://fancy.klade.lv/
 * Version: 1.0.0 (25/04/2008)
 * Copyright (c) 2008 Janis Skarnelis
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Requires: jQuery v1.2.1 or later
*/
(function($) {
    var opts = {},
        imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'],
        loadingTimer, loadingFrame = 1;

   $.fn.fancybox = function(settings) {
        opts.settings = $.extend({}, $.fn.fancybox.defaults, settings);

        $.fn.fancybox.init();

        return this.each(function() {
            var $this = $(this);
            var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings;

            $this.unbind('click').click(function() {
                $.fn.fancybox.start(this, o); return false;
            });
        });
    };

    $.fn.fancybox.start = function(el, o) {
        if (opts.animating) return false;

        if (o.overlayShow) {
            $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>');
            $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity});

            if ($.browser.msie) {
                $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>');
                $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0});
            }

            $("#fancy_overlay").click($.fn.fancybox.close);
        }

        opts.itemArray  = [];
        opts.itemNum    = 0;

        if (jQuery.isFunction(o.itemLoadCallback)) {
           o.itemLoadCallback.apply(this, [opts]);

            var c   = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
            var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}

           for (var i = 0; i < opts.itemArray.length; i++) {
                opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o);

                if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
                    opts.itemArray[i].orig = tmp;
                }
           }

        } else {
            if (!el.rel || el.rel == '') {
                var item = {url: el.href, title: el.title, o: o};

                if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
                    var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
                    item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
                }

                opts.itemArray.push(item);

            } else {
                var arr = $("a[rel=" + el.rel + "]").get();

                for (var i = 0; i < arr.length; i++) {
                    var tmp     = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o;
                    var item    = {url: arr[i].href, title: arr[i].title, o: tmp};

                    if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
                        var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el);

                        item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
                    }

                    if (arr[i].href == el.href) opts.itemNum = i;

                    opts.itemArray.push(item);
                }
            }
        }

        $.fn.fancybox.changeItem(opts.itemNum);
    };

    $.fn.fancybox.changeItem = function(n) {
        $.fn.fancybox.showLoading();

        opts.itemNum = n;

        $("#fancy_nav").empty();
        $("#fancy_outer").stop();
        $("#fancy_title").hide();
        $(document).unbind("keydown");

        imgRegExp = imgTypes.join('|');
        imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i');

        var url = opts.itemArray[n].url;

        if (url.match(/#/)) {
            var target = window.location.href.split('#')[0]; target = url.replace(target,'');

            $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>');

            $("#fancy_loading").hide();

        } else if (url.match(imgRegExp)) {
            $(imgPreloader).unbind('load').bind('load', function() {
                $("#fancy_loading").hide();

                opts.itemArray[n].o.frameWidth  = imgPreloader.width;
                opts.itemArray[n].o.frameHeight = imgPreloader.height;

                $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />');

            }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) );



        } else {
            $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>');
        }
    };

    $.fn.fancybox.showIframe = function() {
        $("#fancy_loading").hide();
        $("#fancy_frame").show();
    };

    $.fn.fancybox.showItem = function(val) {
        $.fn.fancybox.preloadNeighborImages();

        var viewportPos = $.fn.fancybox.getViewport();
        var itemSize    = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight);

        var itemLeft    = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20;
        var itemTop     = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40;


        var itemOpts = {
            'left':     itemLeft + 'px',
            'top':      itemTop + 'px',
            'width':    itemSize[0] + 'px',
            'height':   itemSize[1] + 'px'
        }

        if (opts.active) {
            $('#fancy_content').fadeOut("normal", function() {
                $("#fancy_content").empty();

                $("#fancy_outer").animate(itemOpts, "normal", function() {
                    $("#fancy_content").append($(val)).fadeIn("normal");
                    $.fn.fancybox.updateDetails();
                });
            });

        } else {
            opts.active = true;

            $("#fancy_content").empty();

            if ($("#fancy_content").is(":animated")) {
                console.info('animated!');
            }

            if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) {
                opts.animating      = true;
                itemOpts.opacity    = "show";

                $("#fancy_outer").css({
                    'top':      opts.itemArray[opts.itemNum].orig.pos.top - 18,
                    'left':     opts.itemArray[opts.itemNum].orig.pos.left - 18,
                    'height':   opts.itemArray[opts.itemNum].orig.height,
                    'width':    opts.itemArray[opts.itemNum].orig.width
                });

                $("#fancy_content").append($(val)).show();

                $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() {
                    opts.animating = false;
                    $.fn.fancybox.updateDetails();
                });

            } else {
                $("#fancy_content").append($(val)).show();
                $("#fancy_outer").css(itemOpts).show();
                $.fn.fancybox.updateDetails();
            }
         }
    };

    $.fn.fancybox.updateDetails = function() {
        $("#fancy_bg,#fancy_close").show();

        if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') {
            $('#fancy_title div').html(opts.itemArray[opts.itemNum].title);
            $('#fancy_title').show();
            $('#fancy_title').css("bottom", -$('#fancy_title').height());
        }

        if (opts.itemArray[opts.itemNum].o.hideOnContentClick) {
            $("#fancy_content").click($.fn.fancybox.close);
        } else {
            $("#fancy_content").unbind('click');
        }

        if (opts.itemNum != 0) {
            $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>');

            $('#fancy_left').click(function() {
                $.fn.fancybox.changeItem(opts.itemNum - 1); return false;
            });
        }

        if (opts.itemNum != (opts.itemArray.length - 1)) {
            $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>');

            $('#fancy_right').click(function(){
                $.fn.fancybox.changeItem(opts.itemNum + 1); return false;
            });
        }

        $(document).keydown(function(event) {
            if (event.keyCode == 27) {
                $.fn.fancybox.close();

            } else if(event.keyCode == 37 && opts.itemNum != 0) {
                $.fn.fancybox.changeItem(opts.itemNum - 1);

            } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) {
                $.fn.fancybox.changeItem(opts.itemNum + 1);
            }
        });
    };

    $.fn.fancybox.preloadNeighborImages = function() {
        if ((opts.itemArray.length - 1) > opts.itemNum) {
            preloadNextImage = new Image();
            preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url;
        }

        if (opts.itemNum > 0) {
            preloadPrevImage = new Image();
            preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url;
        }
    };

    $.fn.fancybox.close = function() {
        if (opts.animating) return false;

        $(imgPreloader).unbind('load');
        $(document).unbind("keydown");

        $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide();

        $("#fancy_nav").empty();

        opts.active = false;

        if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) {
            var itemOpts = {
                'top':      opts.itemArray[opts.itemNum].orig.pos.top - 18,
                'left':     opts.itemArray[opts.itemNum].orig.pos.left - 18,
                'height':   opts.itemArray[opts.itemNum].orig.height,
                'width':    opts.itemArray[opts.itemNum].orig.width,
                'opacity':  'hide'
            };

            opts.animating = true;

            $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() {
                $("#fancy_content").hide().empty();
                $("#fancy_overlay,#fancy_bigIframe").remove();
                opts.animating = false;
            });

        } else {
            $("#fancy_outer").hide();
            $("#fancy_content").hide().empty();
            $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove();
        }
    };

    $.fn.fancybox.showLoading = function() {
        clearInterval(loadingTimer);

        var pos = $.fn.fancybox.getViewport();

        $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show();
        $("#fancy_loading").bind('click', $.fn.fancybox.close);

        loadingTimer = setInterval($.fn.fancybox.animateLoading, 66);
    };

    $.fn.fancybox.animateLoading = function(el, o) {
        if (!$("#fancy_loading").is(':visible')){
            clearInterval(loadingTimer);
            return;
        }

        $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px');

        loadingFrame = (loadingFrame + 1) % 12;
    };

    $.fn.fancybox.init = function() {
        if (!$('#fancy_wrap').length) {
            $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body");
            $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner");

            $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title');
        }

        if ($.browser.msie) {
            $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>');
        }

        if (jQuery.fn.pngFix) $(document).pngFix();

        $("#fancy_close").click($.fn.fancybox.close);
    };

    $.fn.fancybox.getPosition = function(el) {
        var pos = el.offset();

        pos.top += $.fn.fancybox.num(el, 'paddingTop');
        pos.top += $.fn.fancybox.num(el, 'borderTopWidth');

        pos.left += $.fn.fancybox.num(el, 'paddingLeft');
        pos.left += $.fn.fancybox.num(el, 'borderLeftWidth');

        return pos;
    };

    $.fn.fancybox.num = function (el, prop) {
        return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
    };

    $.fn.fancybox.getPageScroll = function() {
        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;
        }

        return [xScroll, yScroll];
    };

    $.fn.fancybox.getViewport = function() {
        var scroll = $.fn.fancybox.getPageScroll();

        return [$(window).width(), document.getElementsByTagName('html')[0].clientHeight, scroll[0], scroll[1]];
    };

    $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) {
        var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight);

        return [Math.round(r * imageWidth), Math.round(r * imageHeight)];
    };

    $.fn.fancybox.defaults = {
        hideOnContentClick: false,
        zoomSpeedIn:        500,
        zoomSpeedOut:       500,
        frameWidth:         600,
        frameHeight:        400,
        overlayShow:        false,
        overlayOpacity:     0.4,
        itemLoadCallback:   null
    };
})(jQuery);




/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 */
(function($) {

jQuery.fn.pngFix = function(settings) {

    // Settings
    settings = jQuery.extend({
        blankgif: 'blank.gif'
    }, settings);

    var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
    var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

    if (jQuery.browser.msie && (ie55 || ie6)) {

        //fix images with png-source
        jQuery(this).find("img[src$=.png]").each(function() {

            jQuery(this).attr('width',jQuery(this).width());
            jQuery(this).attr('height',jQuery(this).height());

            var prevStyle = '';
            var strNewHTML = '';
            var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
            var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
            var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
            var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
            var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
            var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
            if (this.style.border) {
                prevStyle += 'border:'+this.style.border+';';
                this.style.border = '';
            }
            if (this.style.padding) {
                prevStyle += 'padding:'+this.style.padding+';';
                this.style.padding = '';
            }
            if (this.style.margin) {
                prevStyle += 'margin:'+this.style.margin+';';
                this.style.margin = '';
            }
            var imgStyle = (this.style.cssText);

            strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
            strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
            strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
            strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
            strNewHTML += imgStyle+'"></span>';
            if (prevStyle != ''){
                strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
            }

            jQuery(this).hide();
            jQuery(this).after(strNewHTML);

        });

        // fix css background pngs
        jQuery(this).find("*").each(function(){
            var bgIMG = jQuery(this).css('background-image');
            if(bgIMG.indexOf(".png")!=-1){
                var iebg = bgIMG.split('url("')[1].split('")')[0];
                jQuery(this).css('background-image', 'none');
                jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
            }
        });

        //fix input with png-source
        jQuery(this).find("input[src$=.png]").each(function() {
            var bgIMG = jQuery(this).attr('src');
            jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
        jQuery(this).attr('src', settings.blankgif)
        });

    }

    return jQuery;

};

})(jQuery);





/*
 * jQuery Tooltip plugin 1.2
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jorn Zaefferer
 *
 * $Id: jquery.tooltip.js 4569 2008-01-31 19:36:35Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function($) {

        // the tooltip element
    var helper = {},
        // the current tooltipped element
        current,
        // the title of the current element, used for restoring
        title,
        // timeout id for delayed tooltips
        tID,
        // IE 5.5 or 6
        IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
        // flag for mouse tracking
        track = false;

    $.tooltip = {
        blocked: false,
        defaults: {
            delay: 200,
            showURL: true,
            extraClass: "",
            top: 15,
            left: 15,
            id: "tooltip"
        },
        block: function() {
            $.tooltip.blocked = !$.tooltip.blocked;
        }
    };

    $.fn.extend({
        tooltip: function(settings) {
            settings = $.extend({}, $.tooltip.defaults, settings);
            createHelper(settings);
            return this.each(function() {
                    $.data(this, "tooltip-settings", settings);
                    // copy tooltip into its own expando and remove the title
                    this.tooltipText = this.title;
                    $(this).removeAttr("title");
                    // also remove alt attribute to prevent default tooltip in IE
                    this.alt = "";
                })
                .hover(save, hide)
                .click(hide);
        },
        fixPNG: IE ? function() {
            return this.each(function () {
                var image = $(this).css('backgroundImage');
                if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
                    image = RegExp.$1;
                    $(this).css({
                        'backgroundImage': 'none',
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
                    }).each(function () {
                        var position = $(this).css('position');
                        if (position != 'absolute' && position != 'relative')
                            $(this).css('position', 'relative');
                    });
                }
            });
        } : function() { return this; },
        unfixPNG: IE ? function() {
            return this.each(function () {
                $(this).css({'filter': '', backgroundImage: ''});
            });
        } : function() { return this; },
        hideWhenEmpty: function() {
            return this.each(function() {
                $(this)[ $(this).html() ? "show" : "hide" ]();
            });
        },
        url: function() {
            return this.attr('href') || this.attr('src');
        }
    });

    function createHelper(settings) {
        // there can be only one tooltip helper
        if( helper.parent )
            return;
        // create the helper, h3 for title, div for url
        helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
            // add to document
            .appendTo(document.body)
            // hide it at first
            .hide();

        // apply bgiframe if available
        if ( $.fn.bgiframe )
            helper.parent.bgiframe();

        // save references to title and url elements
        helper.title = $('h3', helper.parent);
        helper.body = $('div.body', helper.parent);
        helper.url = $('div.url', helper.parent);
    }

    function settings(element) {
        return $.data(element, "tooltip-settings");
    }

    // main event handler to start showing tooltips
    function handle(event) {
        // show helper, either with timeout or on instant
        if( settings(this).delay )
            tID = setTimeout(show, settings(this).delay);
        else
            show();

        // if selected, update the helper position when the mouse moves
        track = !!settings(this).track;
        $(document.body).bind('mousemove', update);

        // update at least once
        update(event);
    }

    // save elements title before the tooltip is displayed
    function save() {
        // if this is the current source, or it has no title (occurs with click event), stop
        if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
            return;

        // save current
        current = this;
        title = this.tooltipText;

        if ( settings(this).bodyHandler ) {
            helper.title.hide();
            var bodyContent = settings(this).bodyHandler.call(this);
            if (bodyContent.nodeType || bodyContent.jquery) {
                helper.body.empty().append(bodyContent)
            } else {
                helper.body.html( bodyContent );
            }
            helper.body.show();
        } else if ( settings(this).showBody ) {
            var parts = title.split(settings(this).showBody);
            helper.title.html(parts.shift()).show();
            helper.body.empty();
            for(var i = 0, part; part = parts[i]; i++) {
                if(i > 0)
                    helper.body.append("<br/>");
                helper.body.append(part);
            }
            helper.body.hideWhenEmpty();
        } else {
            helper.title.html(title).show();
            helper.body.hide();
        }

        // if element has href or src, add and show it, otherwise hide it
        if( settings(this).showURL && $(this).url() )
            helper.url.html( $(this).url().replace('http://', '') ).show();
        else
            helper.url.hide();

        // add an optional class for this tip
        helper.parent.addClass(settings(this).extraClass);

        // fix PNG background for IE
        if (settings(this).fixPNG )
            helper.parent.fixPNG();

        handle.apply(this, arguments);
    }

    // delete timeout and show helper
    function show() {
        tID = null;
        helper.parent.show();
        update();
    }

    /**
     * callback for mousemove
     * updates the helper position
     * removes itself when no current element
     */
    function update(event)  {
        if($.tooltip.blocked)
            return;

        // stop updating when tracking is disabled and the tooltip is visible
        if ( !track && helper.parent.is(":visible")) {
            $(document.body).unbind('mousemove', update)
        }

        // if no current element is available, remove this listener
        if( current == null ) {
            $(document.body).unbind('mousemove', update);
            return;
        }

        // remove position helper classes
        helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");

        var left = helper.parent[0].offsetLeft;
        var top = helper.parent[0].offsetTop;
        if(event) {
            // position the helper 15 pixel to bottom right, starting from mouse position
            left = event.pageX + settings(current).left;
            top = event.pageY + settings(current).top;
            helper.parent.css({
                left: left + 'px',
                top: top + 'px'
            });
        }

        var v = viewport(),
            h = helper.parent[0];
        // check horizontal position
        if(v.x + v.cx < h.offsetLeft + h.offsetWidth) {
            left -= h.offsetWidth + 20 + settings(current).left;
            helper.parent.css({left: left + 'px'}).addClass("viewport-right");
        }
        // check vertical position
        if(v.y + v.cy < h.offsetTop + h.offsetHeight) {
            top -= h.offsetHeight + 20 + settings(current).top;
            helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
        }
    }

    function viewport() {
        return {
            x: $(window).scrollLeft(),
            y: $(window).scrollTop(),
            cx: $(window).width(),
            cy: $(window).height()
        };
    }

    // hide helper and restore added classes and the title
    function hide(event) {
        if($.tooltip.blocked)
            return;
        // clear timeout if possible
        if(tID)
            clearTimeout(tID);
        // no more current element
        current = null;

        helper.parent.hide().removeClass( settings(this).extraClass );

        if( settings(this).fixPNG )
            helper.parent.unfixPNG();
    }

    $.fn.Tooltip = $.fn.tooltip;

})(jQuery);


jQuery.fn.accessNews = function(settings) {
    settings = jQuery.extend({
        newsHeadline: "Top Stories",
        newsSpeed: "normal"
    }, settings);
    return this.each(function(i) {
        aNewsSlider.itemWidth = parseInt(jQuery(".item:eq(" + i + ")",".news_slider").css("width")) + parseInt(jQuery(".item:eq(" + i + ")",".news_slider").css("margin-right"));
        aNewsSlider.init(settings,this);
        jQuery(".view_all > a", this).click(function() {
            aNewsSlider.vAll(settings,this);
            return false;
        });
    });
};
var aNewsSlider = {
    itemWidth: 0,
    init: function(s,p) {
        jQuery(".messaging",p).css("display","none");
        itemLength = jQuery(".item",p).length;
        if (jQuery(".view_all",p).width() == null) {
            jQuery(".news_items",p).prepend("<p class='view_all'>" + s.newsHeadline + " [ всего: " + itemLength + " ]</p>");
        }
        newsContainerWidth = itemLength * aNewsSlider.itemWidth;
        jQuery(".container",p).css("width",newsContainerWidth + "px");
        jQuery(".next",p).css("display","block");
        if (parseInt(jQuery(".container",p).css("left")) + parseInt(jQuery(".container",p).css("width")) <= aNewsSlider.itemWidth * 1) {
            jQuery(".next",p).css("display","none");
        }
        animating = false;
        jQuery(".next",p).click(function() {
            if (animating == false) {
                animating = true;
                animateLeft = parseInt(jQuery(".container",p).css("left")) - (aNewsSlider.itemWidth * 1);
                if (animateLeft + parseInt(jQuery(".container",p).css("width")) > 0) {
                    jQuery(".prev",p).css("display","block");
                    jQuery(".container",p).animate({left: animateLeft}, s.newsSpeed, function() {
                        jQuery(this).css("left",animateLeft);
                        if (parseInt(jQuery(".container",p).css("left")) + parseInt(jQuery(".container",p).css("width")) <= aNewsSlider.itemWidth * 1) {
                            jQuery(".next",p).css("display","none");
                        }
                        animating = false;
                    });
                } else {
                    animating = false;
                }
            }
            return false;
        });
        jQuery(".prev",p).click(function() {
            if (animating == false) {
                animating = true;
                animateLeft = parseInt(jQuery(".container",p).css("left")) + (aNewsSlider.itemWidth * 1);
                if ((animateLeft + parseInt(jQuery(".container",p).css("width"))) <= parseInt(jQuery(".container",p).css("width"))) {
                    jQuery(".next",p).css("display","block");
                    jQuery(".container",p).animate({left: animateLeft}, s.newsSpeed, function() {
                        jQuery(this).css("left",animateLeft);
                        if (parseInt(jQuery(".container",p).css("left")) == 0) {
                            jQuery(".prev",p).css("display","none");
                        }
                        animating = false;
                    });
                } else {
                    animating = false;
                }
            }
            return false;
        });
    },
    vAll: function(s,p) {
        var o = p;
        while (p) {
            p = p.parentNode;
            if (jQuery(p).attr("class") != undefined && jQuery(p).attr("class").indexOf("news_slider") != -1) {
                break;
            }
        }
        if (jQuery(o).text().indexOf("Показать больше") != -1) {
            jQuery(".next",p).css("display","none");
            jQuery(".prev",p).css("display","none");
            jQuery(o).text("Показать меньше");
            jQuery(".container",p).css("left","0px").css("width",aNewsSlider.itemWidth * 1 + "px");
        } else {
            //jQuery(o).text("Показать больше");
            aNewsSlider.init(s,p);
        }
    }
};


/*
 * Treeview 1.4 - jQuery plugin to hide and show branches of a tree
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 * http://docs.jquery.com/Plugins/Treeview
 *
 * Copyright (c) 2007 Jorn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.treeview.js 4684 2008-02-07 19:08:06Z joern.zaefferer $
 *
 */

;(function($) {

    $.extend($.fn, {
        swapClass: function(c1, c2) {
            var c1Elements = this.filter('.' + c1);
            this.filter('.' + c2).removeClass(c2).addClass(c1);
            c1Elements.removeClass(c1).addClass(c2);
            return this;
        },
        replaceClass: function(c1, c2) {
            return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
        },
        hoverClass: function(className) {
            className = className || "hover";
            return this.hover(function() {
                $(this).addClass(className);
            }, function() {
                $(this).removeClass(className);
            });
        },
        heightToggle: function(animated, callback) {
            animated ?
                this.animate({ height: "toggle" }, animated, callback) :
                this.each(function(){
                    jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
                    if(callback)
                        callback.apply(this, arguments);
                });
        },
        heightHide: function(animated, callback) {
            if (animated) {
                this.animate({ height: "hide" }, animated, callback);
            } else {
                this.hide();
                if (callback)
                    this.each(callback);
            }
        },
        prepareBranches: function(settings) {
            if (!settings.prerendered) {
                // mark last tree items
                this.filter(":last-child:not(ul)").addClass(CLASSES.last);
                // collapse whole tree, or only those marked as closed, anyway except those marked as open
                this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
            }
            // return all items with sublists
            return this.filter(":has(>ul)");
        },
        applyClasses: function(settings, toggler) {
            this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event) {
                toggler.apply($(this).next());
            }).add( $("a", this) ).hoverClass();

            if (!settings.prerendered) {
                // handle closed ones first
                this.filter(":has(>ul:hidden)")
                        .addClass(CLASSES.expandable)
                        .replaceClass(CLASSES.last, CLASSES.lastExpandable);

                // handle open ones
                this.not(":has(>ul:hidden)")
                        .addClass(CLASSES.collapsable)
                        .replaceClass(CLASSES.last, CLASSES.lastCollapsable);

                // create hitarea
                this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea).each(function() {
                    var classes = "";
                    $.each($(this).parent().attr("class").split(" "), function() {
                        classes += this + "-hitarea ";
                    });
                    $(this).addClass( classes );
                });
            }

            // apply event to hitarea
            this.find("div." + CLASSES.hitarea).click( toggler );
        },
        treeview: function(settings) {

            settings = $.extend({
                cookieId: "treeview"
            }, settings);

            if (settings.add) {
                return this.trigger("add", [settings.add]);
            }

            if ( settings.toggle ) {
                var callback = settings.toggle;
                settings.toggle = function() {
                    return callback.apply($(this).parent()[0], arguments);
                };
            }

            // factory for treecontroller
            function treeController(tree, control) {
                // factory for click handlers
                function handler(filter) {
                    return function() {
                        // reuse toggle event handler, applying the elements to toggle
                        // start searching for all hitareas
                        toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
                            // for plain toggle, no filter is provided, otherwise we need to check the parent element
                            return filter ? $(this).parent("." + filter).length : true;
                        }) );
                        return false;
                    };
                }
                // click on first element to collapse tree
                $("a:eq(0)", control).click( handler(CLASSES.collapsable) );
                // click on second to expand tree
                $("a:eq(1)", control).click( handler(CLASSES.expandable) );
                // click on third to toggle tree
                $("a:eq(2)", control).click( handler() );
            }

            // handle toggle event
            function toggler() {
                $(this)
                    .parent()
                    // swap classes for hitarea
                    .find(">.hitarea")
                        .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
                        .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
                    .end()
                    // swap classes for parent li
                    .swapClass( CLASSES.collapsable, CLASSES.expandable )
                    .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
                    // find child lists
                    .find( ">ul" )
                    // toggle them
                    .heightToggle( settings.animated, settings.toggle );
                if ( settings.unique ) {
                    $(this).parent()
                        .siblings()
                        // swap classes for hitarea
                        .find(">.hitarea")
                            .replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
                            .replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
                        .end()
                        .replaceClass( CLASSES.collapsable, CLASSES.expandable )
                        .replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
                        .find( ">ul" )
                        .heightHide( settings.animated, settings.toggle );
                }
            }

            function serialize() {
                function binary(arg) {
                    return arg ? 1 : 0;
                }
                var data = [];
                branches.each(function(i, e) {
                    data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
                });
                $.cookie(settings.cookieId, data.join("") );
            }

            function deserialize() {
                var stored = $.cookie(settings.cookieId);
                if ( stored ) {
                    var data = stored.split("");
                    branches.each(function(i, e) {
                        $(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
                    });
                }
            }

            // add treeview class to activate styles
            this.addClass("treeview");

            // prepare branches and find all tree items with child lists
            var branches = this.find("li").prepareBranches(settings);

            switch(settings.persist) {
            case "cookie":
                var toggleCallback = settings.toggle;
                settings.toggle = function() {
                    serialize();
                    if (toggleCallback) {
                        toggleCallback.apply(this, arguments);
                    }
                };
                deserialize();
                break;
            case "location":
                var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); });
                if ( current.length ) {
                    current.addClass("selected").parents("ul, li").add( current.next() ).show();
                }
                break;
            }

            branches.applyClasses(settings, toggler);

            // if control option is set, create the treecontroller and show it
            if ( settings.control ) {
                treeController(this, settings.control);
                $(settings.control).show();
            }

            return this.bind("add", function(event, branches) {
                $(branches).prev()
                    .removeClass(CLASSES.last)
                    .removeClass(CLASSES.lastCollapsable)
                    .removeClass(CLASSES.lastExpandable)
                .find(">.hitarea")
                    .removeClass(CLASSES.lastCollapsableHitarea)
                    .removeClass(CLASSES.lastExpandableHitarea);
                $(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, toggler);
            });
        }
    });

    // classes used by the plugin
    // need to be styled via external stylesheet, see first example
    var CLASSES = $.fn.treeview.classes = {
        open: "open",
        closed: "closed",
        expandable: "expandable",
        expandableHitarea: "expandable-hitarea",
        lastExpandableHitarea: "lastExpandable-hitarea",
        collapsable: "collapsable",
        collapsableHitarea: "collapsable-hitarea",
        lastCollapsableHitarea: "lastCollapsable-hitarea",
        lastCollapsable: "lastCollapsable",
        lastExpandable: "lastExpandable",
        last: "last",
        hitarea: "hitarea"
    };

    // provide backwards compability
    $.fn.Treeview = $.fn.treeview;

})(jQuery);


/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "http://iprim.ru/inc/thickbox/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){
    tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
    imgLoader = new Image();// preload image
    imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
    $(domChunk).click(function(){
    var t = this.title || this.name || null;
    var a = this.href || this.alt;
    var g = this.rel || false;
    tb_show(t,a,g);
    this.blur();
    return false;
    });
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

    try {
        if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
            $("body","html").css({height: "100%", width: "100%"});
            $("html").css("overflow","hidden");
            if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        }else{//all others
            if(document.getElementById("TB_overlay") === null){
                $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        }

        if(tb_detectMacXFF()){
            $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
        }else{
            $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
        }

        if(caption===null){caption="";}
        $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
        $('#TB_load').show();//show loader

        var baseURL;
       if(url.indexOf("?")!==-1){ //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
       }else{
            baseURL = url;
       }

       var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
       var urlType = baseURL.toLowerCase().match(urlString);

        if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images

            TB_PrevCaption = "";
            TB_PrevURL = "";
            TB_PrevHTML = "";
            TB_NextCaption = "";
            TB_NextURL = "";
            TB_NextHTML = "";
            TB_imageCount = "";
            TB_FoundURL = false;
            if(imageGroup){
                TB_TempArray = $("a[@rel="+imageGroup+"]").get();
                for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
                    var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
                        if (!(TB_TempArray[TB_Counter].href == url)) {
                            if (TB_FoundURL) {
                                TB_NextCaption = TB_TempArray[TB_Counter].title;
                                TB_NextURL = TB_TempArray[TB_Counter].href;
                                TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
                            } else {
                                TB_PrevCaption = TB_TempArray[TB_Counter].title;
                                TB_PrevURL = TB_TempArray[TB_Counter].href;
                                TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
                            }
                        } else {
                            TB_FoundURL = true;
                            TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);
                        }
                }
            }

            imgPreloader = new Image();
            imgPreloader.onload = function(){
            imgPreloader.onload = null;

            // Resizing large images - orginal by Christian Montoya edited by me.
            var pagesize = tb_getPageSize();
            var x = pagesize[0] - 150;
            var y = pagesize[1] - 150;
            var imageWidth = imgPreloader.width;
            var imageHeight = imgPreloader.height;
            if (imageWidth > x) {
                imageHeight = imageHeight * (x / imageWidth);
                imageWidth = x;
                if (imageHeight > y) {
                    imageWidth = imageWidth * (y / imageHeight);
                    imageHeight = y;
                }
            } else if (imageHeight > y) {
                imageWidth = imageWidth * (y / imageHeight);
                imageHeight = y;
                if (imageWidth > x) {
                    imageHeight = imageHeight * (x / imageWidth);
                    imageWidth = x;
                }
            }
            // End Resizing

            TB_WIDTH = imageWidth + 30;
            TB_HEIGHT = imageHeight + 60;
            $("#TB_window").append("<a href='' id='TB_ImageOff' title='Закрыть'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Закрыть'>Закрыть</a> или Esc</div>");

            $("#TB_closeWindowButton").click(tb_remove);

            if (!(TB_PrevHTML === "")) {
                function goPrev(){
                    if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
                    $("#TB_window").remove();
                    $("body").append("<div id='TB_window'></div>");
                    tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
                    return false;
                }
                $("#TB_prev").click(goPrev);
            }

            if (!(TB_NextHTML === "")) {
                function goNext(){
                    $("#TB_window").remove();
                    $("body").append("<div id='TB_window'></div>");
                    tb_show(TB_NextCaption, TB_NextURL, imageGroup);
                    return false;
                }
                $("#TB_next").click(goNext);

            }

            document.onkeydown = function(e){
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if(keycode == 27){ // close
                    tb_remove();
                } else if(keycode == 190){ // display previous image
                    if(!(TB_NextHTML == "")){
                        document.onkeydown = "";
                        goNext();
                    }
                } else if(keycode == 188){ // display next image
                    if(!(TB_PrevHTML == "")){
                        document.onkeydown = "";
                        goPrev();
                    }
                }
            };

            tb_position();
            $("#TB_load").remove();
            $("#TB_ImageOff").click(tb_remove);
            $("#TB_window").css({display:"block"}); //for safari using css instead of show
            };

            imgPreloader.src = url;
        }else{//code to show html

            var queryString = url.replace(/^[^\?]+\??/,'');
            var params = tb_parseQuery( queryString );

            TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
            TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
            ajaxContentW = TB_WIDTH - 30;
            ajaxContentH = TB_HEIGHT - 45;

            if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
                    urlNoQuery = url.split('TB_');
                    $("#TB_iframeContent").remove();
                    if(params['modal'] != "true"){//iframe no modal
                        $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Закрыть'>Закрыть</a> или Esc</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
                    }else{//iframe modal
                    $("#TB_overlay").unbind();
                        $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
                    }
            }else{// not an iframe, ajax
                    if($("#TB_window").css("display") != "block"){
                        if(params['modal'] != "true"){//ajax no modal
                        $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>Закрыть</a> или Esc</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
                        }else{//ajax modal
                        $("#TB_overlay").unbind();
                        $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
                        }
                    }else{//this means the window is already up, we are just loading new content via ajax
                        $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
                        $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
                        $("#TB_ajaxContent")[0].scrollTop = 0;
                        $("#TB_ajaxWindowTitle").html(caption);
                    }
            }

            $("#TB_closeWindowButton").click(tb_remove);

                if(url.indexOf('TB_inline') != -1){
                    $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
                    $("#TB_window").unload(function () {
                        $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
                    });
                    tb_position();
                    $("#TB_load").remove();
                    $("#TB_window").css({display:"block"});
                }else if(url.indexOf('TB_iframe') != -1){
                    tb_position();
                    if($.browser.safari){//safari needs help because it will not fire iframe onload
                        $("#TB_load").remove();
                        $("#TB_window").css({display:"block"});
                    }
                }else{
                    $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
                        tb_position();
                        $("#TB_load").remove();
                        tb_init("#TB_ajaxContent a.thickbox");
                        $("#TB_window").css({display:"block"});
                    });
                }

        }

        if(!params['modal']){
            document.onkeyup = function(e){
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if(keycode == 27){ // close
                    tb_remove();
                }
            };
        }

    } catch(e) {
        //nothing here
    }
}

//helper functions below
function tb_showIframe(){
    $("#TB_load").remove();
    $("#TB_window").css({display:"block"});
}

function tb_remove() {
    $("#TB_imageOff").unbind("click");
    $("#TB_closeWindowButton").unbind("click");
    $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
    $("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body","html").css({height: "auto", width: "auto"});
        $("html").css("overflow","");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
    if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
    }
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.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, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
    arrayPageSize = [w,h];
    return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

