//var $jqf = jQuery.noConflict();
//.load().resize();

var dump = function(mixed, type, rec, level) {
    type = type || 'alert';
    if ($.isset(rec) == false) rec = true;
    $.var_dump(mixed, type, rec, level);
};

(function($) {
    $.fn.extend({
        add_hint: function(str) {
            $(this).attr('hint', str);
            $(this).hover(function() {
                $('body').append('<div id="hintdiv"></div>');
                $('#hintdiv').css({
                    position: 'absolute',
                    'background-color': '#FFF5EB',
                    border: '1px solid #000000',
                    padding: 3,
                    opacity: 0
                });
                $('#hintdiv').html($(this).attr('hint'));
                $('#hintdiv').animate({
                    opacity: 1
                }, 'slow');
            }, function() {
                $('#hintdiv').remove();
            });
            $(this).mousemove(function(E) {
                $('#hintdiv').css({
                    top: E.pageY + 15,
                    left: E.pageX + 15
                });
            });
        },
        remove_hint: function() {
        }
    });
})(jQuery);

$(document).ready(function() {
    $.getScript('/scripts/jquery.corner-1.92.js', function(){
    	$.getScript('/scripts/jquery.su-1.0.0.js', function(){

        	$.getScript('/scripts/jquery.togglemenu-0.1.js', function(){
        	    $('#topmenu').createToggleMenu();
        	});

            switch (activePage) {
                case 'home': {
                };
                case 'home':
                case 'news': {
                    buildNewsLine();
                    buildNews();
                    buildRecomendation();
                };
                case 'messages':
                case 'home':
                case 'news': {
                    buildWeektracks();
                    buildPolls();
                    $('#minichat .body').create_shoutbox({use_hotkey:true});
                    break;
                };
                case 'about': {
                    fixContactLists();
                    buildContactLists();
                    if (typeof(activeContactList) == 'undefined') {
                        activeContactList = 'worker';
                    };
                    //activateContactList(activeContactList);
                    break;
                };
                case 'promo': {
                    fixPromoPage();
                    break;
                };
            };
            buildImagesGallery();
        });
    });
    buildAudioPlayer();
});

var get_json = function(uri, data, success, error, complete, beforeSend) {
    $.ajax({
        complete: complete,
        error: error,
        success: success,
        beforeSend: beforeSend,
        cache: false,
        data: data,
        dataType: 'json',
        type: 'POST',
        url: uri
    });
};

/* BEGIN home page functions */
var buildWeektracks = function() {
	$('#weektracks .list tr:odd').css('background-color', '#EEEEEE');
	$('#weektracks .list tr').hover(function(){
		$(this).css('background-color', '#FFF5EB');
	}, function() {
		$('#weektracks .list tr:odd').css('background-color', '#EEEEEE');
		$('#weektracks .list tr:even').css('background-color', 'transparent');
	});
	$('#weektracks .list td.rate div.star').css('cursor', 'pointer');
	$('#weektracks .list td.rate div.star').add_hint(function() {
	    return '+' + $(this).attr('id').split('-')[3];
	});
	$('#weektracks .list td.rate div.star').hover(function(){
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	$('#weektracks .list td.rate div.star').click(function() {
	    var id = $(this).parents('tr').attr('id').split('-')[1];
	    var rate = $(this).attr('id').split('-')[3];
	    get_json('/home/weektracks/rate/', {id: id, rate: rate}, function(data, textStatus) {
	        disableBlockText(data.message);
	        if (typeof(data.positions) == 'object') {
	            //dump(data.positions.length);
	            refreshWeektracks(data.positions);
	        };
	    }, function(XMLHttpRequest, textStatus, errorThrown) {
	        disableBlockText('Error: ' + textStatus);
	    }, '', function(XMLHttpRequest) {
	        disableBlock('#weektracks .list:first');
	        disableBlockText('Sending your vote...', -1);
	    });
	});

	var refreshWeektracks = function(pos) {
        for (i in pos) {
            var c = $('#track-' + pos[i].id).clone(true);
            $('#track-' + pos[i].id).remove();
            $('#weektracks .list').append(c);
            c.find('td.number').text(parseInt(i) + 1);
            rateWeektracks(c, pos[i].rate);
        };
	};
	var rateWeektracks = function(track, rate) {
	    track = track || 0;
	    rate = rate || 0;
	    if (track < 1 || rate < 1) return false;
	    $('div.star', track).each(function(k, v) {
	        $(this).removeClass('hover');
	        (k < rate) ? $(this).addClass('active') : $(this).removeClass('active');
	    });
	};
};

var disableBlockText = function(text, time) {
    time = time || 2000;
    /*var oldtext = $('#disableBlock-span').html();
    if (oldtext != '') oldtext += '<BR />';
    $('#disableBlock-span').html(oldtext + '> ' + text);*/
    $('#disableBlock-span').html(text);
    var h = $('#disableBlock-span').height();
    var height = $('#disableBlock').height();
    $('#disableBlock-span').css({
        top: (height - h) / 2 - 5
    });
    if (time != -1) {
        window.setTimeout(function() {
            $('#disableBlock').remove();
        }, time);
    };
};
var disableBlock = function(obj) {
    obj = obj || 'body';
    if ($('#disableBlock').length > 0) {
        $('#disableBlock').remove();
    };
    $(obj).prepend('<div id="disableBlock"><img src="/images/disablehtml.gif" alt="" id="disableBlock-img" /><span id="disableBlock-span"></span>   </div>');

    var o = $(obj).offset();
    var d = {
        width: $(obj).innerWidth() - 2,
        height: $(obj).innerHeight() - 2
    };
    if ($.browser.msie == false) {
        d.height -= 13;
    };

    $('#disableBlock').css({
                     cursor: 'default',
                     overflow: 'hidden',
                     position: 'absolute',
                     width: d.width,
                     height: d.height,
                     top: o.top + 1,
                     left: o.left + 1,
                     'z-index': 6660
                     });
    $('#disableBlock-img').css({
                     width: d.width,
                     height: d.height,
                     opacity: .9,
                     'z-index': 6661
                     });

    $('#disableBlock-span').css({
                     position: 'absolute',
                     width: d.width - 20,
                     top: 0,
                     left: 0,
                     display: 'block',
                     color: 'red',
                     padding: '5px 10px',
                     'text-align': 'center',
                     'font-weight': 'bold',
                     'z-index': 6662
                     });

    return $('#disableBlock');
};

var buildPolls = function() {
    $('#polls .votes_result').css({
        opacity: .2
    });
    $('#polls .vote .body').add_hint(function() {
        return 'Результат - ' + $('.votes_percent', this).text() + '<BR />Голосов - ' + $('.votes_count', this).text().split(': ')[1];
    });
    $('#polls .votes_desc').css({
        position: 'relative',
        top: '-70px',
        padding: '0px 5px'
    });
    $('#polls .votes_desc').each(function() {
        var h = $(this).parent().height();
        h = h - (h > 140 ? 70 : h - 70);
        $(this).parent().height(h);
    });
    var destroy_accordion = function(){
        var groups = $('.mcb-acc-group', $('#poll_votes'));
        var settings = {
            group: '.vote',
            body: '.body',
            header: '.header',
            activeClass: 'block_002_active',
            alwaysOpen: false,
            //singleOpen: false,
    		active: false
        };
        groups.each(function() {
            $(this).removeClass(settings.activeClass);
            $(this).removeClass('mcb-acc-group');
            $(this).find(settings.body).removeClass('mcb-acc-body');
            $(this).find(settings.header).removeClass('mcb-acc-header');
            $(this).find(settings.header).removeClass('mcb-acc-header');
        });
        //$('#poll_votes').maccordion('destroy');
    };
    var create_accordion = function(active){
        active = active || false;
        $('#poll_votes .vote .body').css({overflow: 'hidden'});
        $('#poll_votes').maccordion({
            group: '.vote',
            body: '.body',
            header: '.header',
            activeClass: 'block_002_active',
            alwaysOpen: false,
            singleOpen: false,
    		active: active
        });
        $('#poll_votes input').click(function(E) {
            $.data($('body').get(0), 'poll_click_handler', 'input');
            $.data($('body').get(0), 'poll_click_handler_state', this.checked);
            $.data($('body').get(0), 'poll_click_handler_parent_id', $(this).parents('.vote').attr('id'));
        });
    };
    $.getScript('/scripts/jquery.mcb.accordion-1.0.0.js', function() {
        create_accordion();
    });
    $('#polls form').submit(function(E) {
        E.preventDefault();
        var data = $(this).serializeArray();
        if (typeof(data) == 'object' && data.length == 0) {// || data == ''
            disableBlock('#polls .body:first');
	        disableBlockText('ОШ�?БКА: Вы не выбрали ответ!');
	        return false;
        }
        var poll_id = $(this).attr('id').split('_')[1];
        data.push({name: 'id', value: poll_id});
        get_json('/home/polls/vote/', data, function(data, textStatus) {
            //dump(data, '', true, 5);
	        disableBlockText(data.message);
	        if (typeof(data.votes_results) == 'object' && typeof(data.votes_count) != 'undefined') {
	            //dump(data.votes_results);
	            refreshPolls(poll_id, data.votes_results, data.votes_count);
	        };
	    }, function(XMLHttpRequest, textStatus, errorThrown) {
	        disableBlockText('ОШ�?БКА: ' + textStatus);
	        dump(XMLHttpRequest.responseText);
	    }, '', function(XMLHttpRequest) {
            disableBlock('#polls .body:first');
	        disableBlockText('Данные отправлены, ждем ответа...', -1);
	    });
    });
/*
	var refreshPolls = function(poll, results, count) {
	    if (results.length < 2) {
	        return false;
	    };
	    $.each(results, function(k, v) {
	        alert(k);
	    });
	};
*/
	var refreshPolls = function(poll, results, count) {
	    for (i in results) {
            $('#vote-' + results[i].vote_id)
                .remove()
                .clone(true)
                .attr('id', 'vote-' + results[i].vote_id)
                .appendTo($('#poll_votes'));
            setVoteResult(results[i].vote_id, results[i].results_count, count);
        };
        $('#poll_votes .vote input').attr('checked', false);
        $.removeData($('body').get(0), 'poll_click_handler');
        $.removeData($('body').get(0), 'poll_click_handler_state');
        $.removeData($('body').get(0), 'poll_click_handler_parent_id');
        var active = [];
        $('#poll_votes .block_002_active').each(function(k, v) {
            active.push('#' + $(this).attr('id'));
        });
        //dump(active);
        destroy_accordion();
        create_accordion(typeof(active) != 'undefined' ? active : false);
        $('#polls .vote .body').add_hint(function() {
            return 'Результат - ' + $('.votes_percent', this).text() + '<BR />Голосов - ' + $('.votes_count', this).text().split(': ')[1];
        });
	};
/*
	var refreshPolls = function(poll, results, count) {
	    //dump(results);
	    var active = $('#poll_votes .block_002_active').attr('id');
	    destroy_accordion();
	    var h = $('#poll_votes').height();
	    var r = $('#poll_votes .vote:first').clone(true);
	    $('#poll_votes').empty();
	    $('#poll_votes').height(h);
	    for (i in results) {
	        var n = r.clone();
	        n.attr('id', 'vote-' + results[i].vote_id);
	        $('#poll_votes').append(n.show());
	    };
	    //dump($('#poll_votes').html());
	    $('#poll_votes').height('auto');
	    //typeof(active) != 'undefined' ? '#' + active : false
	    create_accordion();
	};
*/
	var setVoteResult = function(id, result, count) {
	    $('#vote-' + id + ' .votes_percent').text(percents(result, count));
	    $('#vote-' + id + ' .votes_count').text('Голосов: ' + result);
	};
};

var percents = function(value, total, suffix) {
    suffix = suffix || '%';
    var ret = total > 0 ? Math.round(value / total * 100) : 0;
    return ret + suffix;
};

var buildNews = function() {
    $.getScript('/scripts/jquery.mcb.accordion-1.0.0.js', function(){
        $('#news .body').maccordion({
            group: '.news',
            body: '.body',
            header: '.header',
            activeClass: 'block_002_active',
            autoHeight: false,
            active: active_news_group > 0 ? active_news_group - 1 : ':first'
        });
    });
    $('.last_news .image').corner("10px");
    $('.news .desc img').each(function() {
        if ($(this).width() > 500 && $(this).hasClass('thumb') == false) {
            $(this).width(500);
        };
    });
};
var buildNewsLine = function() {
    $.getScript('/scripts/jquery.mcb.newsline-1.0.0.js', function(){
        $('#news .body ul').newsline({
            group: 'li',
            body: 'a.icon',
            header: 'a.title'
        });
    });
};
var buildRecomendation = function() {
    $.getScript('/scripts/ui.core.packed.js', function(){
    	$.getScript('/scripts/ui.accordion.packed.js', function(){
    	    $('#recomendation .body .recomendation .body').show();
		    $('#recomendation .body').accordion({
    	        header: '.header',
    	        selectedClass: 'block_002_active',
    	        alwaysOpen: false,
    	        active: false
		    });
    	    //$('.recomendation:first').addClass('block_002_active');
    	});
	});
};
var buildPromo = function() {
};
/* END home page functions */

/* BEGIN about page functions */
var activateContactList = function(group) {
    group = group || 'worker';
    deactivateContactLists();

    $('#' + group + '_list .header, #' + group + '_list_tmp .header').addClass('header_active');
    $('#' + group + '_list, #' + group + '_list .body').show();

    if ($('#' + group + '_list .body tr.row1').height() < 150) {
        $('#' + group + '_list .body tr.row1').height(150);
    };
    //$('#' + group + '_list .body tr.row2').height($('#content').height() - $('#' + group + '_list .body tr.row1').height() - 63);
    //$('#' + group + '_list .body div.hr').height($('#content').height() - $('#' + group + '_list .body tr.row1').height() - 71);
    $('#' + group + '_list .body div.hr').height($('#' + group + '_list .body tr.row2').height());
};
var deactivateContactLists = function(group) {
    $('.contacts_list .header, #top_list_tmp .header, #worker_list_tmp .header').removeClass('header_active');
    $('.contacts_list, .contacts_list .body').hide();
};
var fixContactLists = function() {
    $('.contacts_list .list li:first').css({'margin-top':'0px'});
    $('.block_002').css({'padding-bottom':'0px'});
};
var buildContactLists = function() {
    $('.contacts_list .avatar .footer').each(function() {
        $(this) .css('cursor', 'pointer')
                .fadeTo(1000, .75)
                .hover(function() {
            $(this).fadeTo(1000, 1);
        }, function() {
            $(this).fadeTo(1000, .75);
        });
    });
};
/* END about page functions */

/* BEGIN promo page functions */
var fixPromoPage = function() {
    $('#active_promo .body').height($('#content').height() - 53);
};
/* END promo page functions */

var disableBody = function() {
    $('body').prepend('<img src="/images/disablehtml.gif" alt="" id="modal" />');
    $('#modal').css({
                     'position': 'absolute',
                     'width': $('body').width(),
                     'height': $('body').height(),
                     'z-index': 6666,
                     'opacity': .9
                     });
    $(window).scroll(function(e) {
        e.preventDefault();
    });

/*	var n = document.createElement("div");
	$(n).attr('id', 'newsss');
	$('#weektracks').append(n);
	alert($('#weektracks').html());*/
/*
	$('.gallery_line').find('.button').animate({opacity:.7}, 100)
	if($('.gallery_line').find('.button').length > 0) {
	    alert($('.gallery_line').find('.button').length);
	}
	$('.gallery_line a')
	    .hover(function () {
	        //$(this).find('.text').css({visibility:'visible'});
	        $(this).find('.button').animate({height:(28 + $(this).find('.text').height()), margin:'-' + (28 + $(this).find('.text').height()) + 'px 0px 0px 0px'}, {duration: $(this).find('.text').height() / 10 * 100});
	        $(this).find('.title').animate({margin:'-' + (28 + $(this).find('.text').height()) + 'px 0px 0px 0px'}, {duration: $(this).find('.text').height() / 10 * 100});
	    }, function () {
	        $(this).find('.button').animate({height:'22px', margin:'-22px 0px 0px 0px'}, {duration: $(this).find('.text').height() / 10 * 200});
	        $(this).find('.title').animate({margin:'-22px 0px 0px 0px'}, {duration: $(this).find('.text').height() / 10 * 200});
	        //$(this).find('.text').css({visibility:'hidden'});
	    });
*/
    	    /*
    	    $('#news .body .news .header').each(function() {
    	        $(this).replaceWith('<a href="#" title="" class="header">' + $(this).html() + '</div>');
    	    });
    	    $('#news .body').accordion({
    	        header: '.header',
    	        selectedClass: 'block_002_active'
    	        //autoHeight: false,
    	        //clearStyle: true
    	    });
    	    $('#news .body .news:first').addClass('block_002_active');
    	    */
};

var buildImagesGallery = function() {
    $('img.thumb').each(function() {
        $(this).wrap('<a href="' + $(this).attr('src') + '" class="lightbox-thumb"></a>');
               //.attr('src', getImageCachePath($(this).attr('src'), $(this).width(), $(this).height(), 'w'));
    });

    $('img.lightbox').each(function() {
        $(this).wrap('<a href="' + $(this).attr('src') + '" class="lightbox"></a>');
               //.attr('src', getImageCachePath($(this).attr('src'), $(this).width(), $(this).height(), 'w'));
    });

    $('a.lightbox, a.lightbox-thumb').lightBox({
		imageLoading: '/images/lightbox/lightbox-ico-loading.gif',
		imageBtnPrev: '/images/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: '/images/lightbox/lightbox-btn-next.gif',
		imageBtnClose: '/images/lightbox/lightbox-btn-close.gif',
		imageBlank: '/images/lightbox/lightbox-blank.gif'
    });
    //alert($('a.lightbox, a.lightbox-thumb').length);
};
var getImageCachePath = function($url, $width, $height, $ratio) {
    $width = $width || 0;
    $height = $height || 0;
    $ratio = $ratio || 'a';
    if ($width == 0 && $height == 0) return FALSE;
    if ($.url.setUrl($url).segment(0) == 'public') {
        $url = $url.replace('/public', '/public/' + $width + 'x' + $height + $ratio);
    };
    return $url;
}

var buildAudioPlayer = function() {
    $('a.audio').each(function() {
			var d = $(document.createElement('div'));
			$(this).hide().after(d);
			$(d).jmp3({
				filepath: $(this).attr('href'),
					showfilename: "false",
					backcolor: "dcdcdc",
					forecolor: "00ff00",
					width: 100,
					showdownload: "false"
					});
    });
};