var logo_fixed_position = $(window).height();

function random(X) {
    return Math.floor(X * (Math.random() % 1));
}

function randomBetween(MinV, MaxV) {
  return MinV + random(MaxV - MinV + 1);
}

function resize(){
    var winWidth = $(window).width();

//    if(winWidth > 690){
        $('#main').width(winWidth);
		var st = winWidth - 150 - 270;
		if (st < 540) {
			$('#menu').css('width', '270px');
		}
		else {
			$('#menu').css('width', '540px');
		}
        //$('#contact').css('margin-left', '15px');
//    }

	if (winWidth <= 960) {
		$('#post-body').addClass('narrow_viewport');
	}
	else {
		$('#post-body').removeClass('narrow_viewport');
	}
}

function rebuildUrl(){
    var cur_address = window.location.href.replace(config['baseUrl'], '');
    var chunks = cur_address.split('/');
    var letter = (author_search == '') ? '' : ('/'+ author_search);
    var medium = (media_category_name == '') ? '' : ('/'+ media_category_name);
    return config['baseUrl']+chunks[0]+'/'+chunks[1]+medium.toLowerCase()+letter.toLowerCase();
}

function language_check(){
    var l_lang;
    if (navigator.userLanguage) // Explorer
        l_lang = navigator.userLanguage.substr(0,2);
    else if (navigator.language) // FF
        l_lang = navigator.language.substr(0,2);
    else
        l_lang = "en";

    //for any langs different from pl, set english
    if(l_lang != 'pl') {
        l_lang = "en";
	}

    top.location = config['baseUrl']+config['langSetUrl']+l_lang;
}


function fixed_positioning() {
	var ptop = $(window).scrollTop() + $(window).height() - 95;
	if (ptop != logo_fixed_position) {
		logo_fixed_position = ptop;
		$('#bottom-logo').css('top', ptop+'px');
	}
}

function goToWithFade(url){
	if(url != ''){
		$('#curtain').fadeIn('fast', function(){
			top.location = url;
		});
	}
	return false;
}


function hideCollectionFields(param){
    if(param){
        $('#intro_pl').val('');
        $('#intro_en').val('');
		$('#intro2_pl').val('');
        $('#intro2_en').val('');

        $('#start_time').val('');
        $('#end_time').val('');
        $('#start_date').val('');
        $('#end_date').val('');
        $('.edit-time').hide();
        $('.edit-date').hide();
    }
    else{
        var date = new Date();
        var day = date.getDate();
        var month = date.getMonth()+1;
        //if(day < 10){
        //    day = "0" + day;
        //}
        //if(month < 10){
        //    month = "0" + month;
        //}

        $('.edit-time').show();
        $('.edit-date').show();
        
//        if ($('#intro_pl').val() == '')
//            $('#intro_pl').val('Bilety: Normalne 15zł; Ulgowe 10zł; Grupowe 7,5zł');
//        if ($('#intro_en').val() == '')
//            $('#intro_en').val('Tickets: Adults 15zł; Infants 10zł; Group 7,5zł');
        if ($('#start_time').val() == '')
            $('#start_time').val(date.getHours()+"."+date.getMinutes());
        if ($('#end_time').val() == '')
            $('#end_time').val(date.getHours()+"."+date.getMinutes());
        if ($('#start_date').val() == '')
            $('#start_date').val(day+"."+month  +"."+date.getFullYear());
        if ($('#end_date').val() == '')
            $('#end_date').val(day+"."+month  +"."+date.getFullYear());
    }
}

function hideStaticFields(param){
    if(param){
		$('#external').show();

		$('#intro_pl').val('');
        $('#intro_en').val('');
		$('#intro2_pl').val('');
        $('#intro2_en').val('');

		$('#intro_container').hide();
        $('#start_time').val('');
        $('#end_time').val('');
        $('#start_date').val('');
        $('#end_date').val('');
        $('.edit-time').hide();
        $('.edit-date').hide();
        $('#sponsors-partners').hide();
        $('.tags-container').hide();
        $('.kuratela').hide();
        $('.edit-places').hide();
        $('#autor').hide();
        $('.text-plus').hide();
        $('#subtitle').hide();
        $('#pagelink').hide();
        $('#attachments').hide();
    }
    else{
		$('#external').hide();
		
		var date = new Date();
        var day = date.getDate();
        var month = date.getMonth()+1;
        //if(day < 10){
        //    day = "0" + day;
        //}
        //if(month < 10){
        //    month = "0" + month;
        //}

		$('#intro_container').show();        
        $('.edit-time').show();
        $('.edit-date').show();
//        if ($('#intro_pl').val() == '')
//            $('#intro_pl').val('Bilety: Normalne 15zł; Ulgowe 10zł; Grupowe 7,5zł');
//        if ($('#intro_en').val() == '')
//            $('#intro_en').val('Tickets: Adults 15zł; Infants 10zł; Group 7,5zł');
         if ($('#start_time').val() == '')
            $('#start_time').val(date.getHours()+"."+date.getMinutes());
        if ($('#end_time').val() == '')
            $('#end_time').val(date.getHours()+"."+date.getMinutes());
        if ($('#start_date').val() == '')
            $('#start_date').val(day+"."+month  +"."+date.getFullYear());
        if ($('#end_date').val() == '')
            $('#end_date').val(day+"."+month  +"."+date.getFullYear());
        $('#sponsors-partners').show();
        $('.tags-container').show();
        $('.kuratela').show();
        $('.edit-places').show();
        $('#autor').show();
        $('.text-plus').show();
        $('#subtitle').show();
        $('#pagelink').show();
        $('#attachments').show();
    }
}

function hideMedia(param){
    if(param){
        $('#media-categories').hide();
    }
    else{
        $('#media-categories').show();
    }
}


$(function() {
	var ie6 = (typeof($.browser.msie) != 'undefined' && $.browser.version.split('.')[0] == '6');
	var iphone = $('#iphone_detection').width() == 200;
	// TODO: fix for ie6 and iphone - position fixed
	if (ie6 || iphone) {
		$('#bottom-logo').css('position', 'absolute');
		fixed_positioning();

		$(window).bind('scroll', function(){
			fixed_positioning();
		}).bind('resize', function() {
			fixed_positioning();
		});
	}

//	var colors = ['#1d6ab2', '#fc1027', '#ff6600', '#1d6ab2', '#fc1027', '#ff6600', '#1d6ab2', '#fc1027', '#ff6600', '#1d6ab2', '#fc1027', '#ff6600', '#1d6ab2', '#fc1027', '#ff6600', '#1d6ab2', '#fc1027', '#ff6600'];
	var colors = ['#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600', '#ff6600'];

	// selects link
	$('#posts a:not(.dropdownLabel):not(.as-close), #post-body a:not(.dropdownLabel):not(.as-close), #contact a, .inputadd, .button_submit, .choose-lang:not(.active), #upload-video-label, #newsletter_message, #email_share_message').live('mouseover', function() {
		$(this).addClass('linkselected');
	});
	$('#posts a:not(.dropdownLabel):not(.as-close), #post-body a:not(.dropdownLabel):not(.as-close), #contact a, .inputadd, .button_submit, .choose-lang:not(.active), #upload-video-label, #newsletter_message, #email_share_message').live('mouseout', function() {
		$(this).removeClass('linkselected');
	});

	// menu
	$('#menu a:not(.dropdownLabel):not(.as-close)').live('mouseover', function() {
		$('#menu .menu-links a.active').removeClass('menuselected');
		$(this).addClass('menuselected');
	});

	$('#menu span.menu-children').live('mouseover', function() {
		$('#' + $(this).attr('class').substr(14)).addClass('menuselected');
	});
	$('#menu span.menu-children').live('mouseout', function() {
		$('#' + $(this).attr('class').substr(14)).removeClass('menuselected');
	});

	$('#menu a:not(.dropdownLabel):not(.as-close)').live('mouseout', function() {
		$(this).removeClass('menuselected');
	});

	$('#menu').bind('mouseleave', function() {
		var id = $('#menu .menu-links a.active').addClass('menuselected').attr('id');
		$('#menu .menu-children').each(function() {
			if ($(this).hasClass(id)) {
				$(this).slideDown('fast');
			}
			else {
				$(this).slideUp('fast');
			}
		});

		// shouldn't slide up if one of children is active
		// and should restore other menu if there is active child
		//$('#menu .menu-children').slideUp('fast');
	});

	$('#menu .menu-links a.active').addClass('menuselected');

//	$('.menu-children a:not(.active)').live('mouseout', function() {$(this).css({'color' : '#939598', 'text-decoration' : 'underline'});});
	//$('.post-title a, #sitemap a').live('mouseout', function() {$(this).css({'color' : '#000', 'text-decoration' : 'none'});});

	$('.choose-lang.active').css({'color' : colors[randomBetween(0,17)], 'text-decoration' : 'none'});

	$('#flashUploadButton').live('mouseover', function() {$('#upload-button-label').css({'color' : colors[randomBetween(0,17)], 'text-decoration' : 'none'});});
	$('#flashUploadButton').live('mouseout', function() {$('#upload-button-label').css({'color' : '#000', 'text-decoration' : 'underline'});});
	$('#flashUploadButton2').live('mouseover', function() {$('#upload-button-label2').css({'color' : colors[randomBetween(0,17)], 'text-decoration' : 'none'});});
	$('#flashUploadButton2').live('mouseout', function() {$('#upload-button-label2').css({'color' : '#000', 'text-decoration' : 'underline'});});

	$('#bottom-logo').live('click', function(){top.location = config['baseUrl'];});



    $('.link-opt').live('click', function(){
        var p=prompt("Podaj pełny link:");
        if(p) {
			if (p.indexOf('http') != 0) {
				p = 'http://' + p;
			}
            document.execCommand('CreateLink', false, p);$(this).parent().siblings('editor').focus();
		}
        return false;
    });

    //$('.active').siblings('.menu-children').show();
	$('.parent.active').parent().siblings('.menu-children').each(function(){
		if($(this).hasClass($('.parent.active').attr('id'))){
			if($(this).html() != ''){
				$(this).show();
			}
		}
	});

	$('.parent').click(function(){
		var parent = $(this);
		var child = null;

		$('.menu-children').each(function(){
			if($(this).hasClass(parent.attr('id'))){
				child = $(this);
				if($(this).html() == ''){
					top.location = parent.attr('href');
					$('#curtain').show();
				}
				else{
					return false;
				}
			}
		});

		//$('.menu-children:not(.'+parent.attr('id')+')').slideUp('fast', function(){child.slideDown('fast')});
		$('.menu-children').each(function(){
			if(!$(this).hasClass(parent.attr('id'))){$(this).slideUp('fast');}
		});
		child.slideToggle('fast');

		$('.search-button').parent().show();
		$('.search').fadeOut('fast');

		return false;
	});

//	$('#menu .menu-links a.active').css('color', colors[randomBetween(0,17)]);

    $('.search-button').click(function(){
        if(!$('.search').visible){
			//$('.menu-children').slideUp('fast');
            $('.search-button').parent().hide();
            $('.search').fadeIn('fast');
            $('.search input').focus();
        }
        else {
            $('.search input').focus();
		}
        return false;
    });



        $('.chekk').each(function(){
            if($(this).is(':checked')){
                $(this).siblings('.checkbox').removeClass('unchecked');
                $(this).siblings('.checkbox').addClass('checked');
                }
        });

        $('.checkbox-container').hover(function(){
            if(!$(this).children('.chekk').is(':checked')){
            $(this).children('.checkbox').removeClass('unchecked');
            $(this).children('.checkbox').addClass('checked');
            }
        }, function(){
            if(!$(this).children('.chekk').is(':checked')){
            $(this).children('.checkbox').removeClass('checked');
            $(this).children('.checkbox').addClass('unchecked');
            }
        });

        $('.checkbox-container').click(function(){
            if($(this).children('.chekk').is(':checked')){
            $(this).children('.chekk').attr('checked',false)
            $(this).children('.checkbox').removeClass('checked');
            $(this).children('.checkbox').addClass('unchecked');
            }
            else{
            $(this).children('.chekk').attr('checked', true);
            $(this).children('.checkbox').addClass('checked');
            $(this).children('.checkbox').removeClass('unchecked');
            }
        });

        $('.checkbox-container').focus(function(){$(this).addClass('outline-check');});
        $('.checkbox-container').blur(function(){$(this).removeClass('outline-check');});
        $('.checkbox-container').keydown(function(event) {
            if (event.keyCode == '32') {
               event.preventDefault();
               if($(this).children('.chekk').is(':checked')){
                  $(this).children('.chekk').attr('checked',false)
                  $(this).children('.checkbox').removeClass('checked');
                  $(this).children('.checkbox').addClass('unchecked');
                  }
                  else{
                  $(this).children('.chekk').attr('checked', true);
                  $(this).children('.checkbox').addClass('checked');
                  $(this).children('.checkbox').removeClass('unchecked');
                  }
             }
        });


		$('.dropdownHidden.collection-letter').live('change', function() {
			var value = $(this).val();
			//console.log(value);

			if(value != 0){
				author_search = value;
			}
			else{
				author_search = '';
			}
			//console.log(rebuildUrl());
			top.location = rebuildUrl();
		});


		$('.dropdownHidden.collection-medium').live('change', function() {
			var value = $(this).val();
			//console.log(value);

			if(value != 0){
				media_category_name = value;
			}
			else{
				media_category_name = '';
			}
			//console.log(rebuildUrl());
			top.location = rebuildUrl();

		});


		$('.dropdownHidden.expo-date').live('change', function() {
			var value = $(this).val();
			//console.log(value);

			top.location = value;

		});


		$('.dropdownHidden.places').live('change', function() {
			var value = $(this).val();
			//console.log(value);

            place_id = value;

		});


		$('.dropdownHidden.section').live('change', function() {
			var value = $(this).val();
			if(value != 0){
				//special treatment for education category
				if(value == 3){
					curCat = value;
					parentCat = value;
					setCategory(value);
					hideMedia(true);
					hideCollectionFields(false);
					hideStaticFields(false);
					$('.category, .editor-links.categories').hide();
				}
				//for static outer pages
				else if(value == 4){
					curCat = value;
					parentCat = value;
					setCategory(value);
					hideStaticFields(true);
                    hideMedia(true);
					$('.category, .editor-links.categories').hide();
				}
                //for expositions
				else if(value == 1){
					curCat = value;
					parentCat = value;
					setCategory(value);
					hideStaticFields(false);
                    hideMedia(true);
					$('.category, .editor-links.categories').hide();
				}
				else{
					hideStaticFields(false);
					getCategories(value);
					parentCat = value;
					if(value == 2){
						hideCollectionFields(true);
						hideMedia(false);
					}
					else{
						hideCollectionFields(false);
						hideMedia(true);
					}
				}
			}

		});


		$('.dropdownHidden.media-cat').live('change', function() {
			var value = $(this).val();
			//console.log(value);

            mediaCat = value;

		});


		$('.dropdownHidden.category').live('change', function() {
			var value = $(this).val();
			//console.log(value);

			curCat = value;
            setCategory(value);

		});

		$('.dropdownHidden.users-dropdown').live('change', function() {
			var value = $(this).val();
			//console.log(value);
            if(value != 0){
				load_user(value);
			}

		});
});

