/* przeniesione z TOP */

function validateYTupload() {
    try {
        if($('#fileToUpload') == undefined || $('#fileToUpload').val() == '') {
            $('#upl_image_filename').html('<span style="font-weight: normal;">Musisz wybrać plik.</span>').show();
            return false;
        } else {
            $('#loading').show();
            return true;
        }
    } catch(ex) {
        return false;
    }
}

function regulationPopUp() {
    window.open('index/regulation/aspopup', 'Regulamin', 'status=0,height=600,width=800,resizable=1,toolbar=0,directories=0,scrollbars=1');
}

function FBlogout(){
   FB.Connect.logout(function(){
      // we are logged out of facebook, erase my app's cookie
       //var name = "name_of_my_session_cookie";
       //document.cookie = name +'=;expires=Thu, 01-Jan-1970 00:00:01 GMT';
     //refresh the main page
     setCookie('aa',55,355);
       //var url = window.location.href;
       var url = 'http://drobne.tv/users/logout';
       //alert(url);
     // append a timestamp to make sure the url seems different to the browser
       //url = (url+(url.indexOf('?') > -1 ? '&' : '?')+(new Date()).getTime());
       //alert(url);
       window.location.href = url;
   });
};

function selectAll() {
	var inputs = document.getElementsByTagName('input');
    var checkboxes = [];
    for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == 'checkbox') {
			inputs[i].checked = true;
		}
	}
}

function deselectAll() {
    var inputs = document.getElementsByTagName('input');
    var checkboxes = [];
    for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == 'checkbox') {
			inputs[i].checked = false;
		}
	}
}


function CheckCatName(id, catId) {
    document.getElementById('category_check_input').value = '';
    document.getElementById('category_check_input').value = document.getElementById(id).innerHTML;
    document.getElementById('cat_id').value = '';
    document.getElementById('cat_id').value = catId;
    CloseCategoryCheck();

}

function CheckCatName6(id, catId) {
    try {
        document.getElementById('subcategory_name').value = '';
        document.getElementById('subcategory_name').innerHTML = document.getElementById(id).innerHTML;
        document.getElementById('subcat_id').value = '';
        document.getElementById('subcat_id').value = catId;
        $('#parent_subcategory_check').slideUp('slow');
    } catch(a) {
        alert(a);
    }
}

function CheckWord(id) {
    document.getElementById('search_word').value = '';
    document.getElementById('search_word').value = document.getElementById(id).innerHTML;
    //CloseWordCheck();
    $('#search_words').hide('slow');
}

function CloseCategoryCheck() {
    $('#search_check_categories').slideToggle('slow');
    //document.getElementById('search_check_categories').innerHTML = '';
}

function CloseWordCheck() {
    document.getElementById('search_words').innerHTML = '';
}

/**
 * Zamyka okno logowania
 */
function CloseLogin() {
    //document.getElementById('log_in').innerHTML = '';
    $('#log_in').hide();
}



function ShowMap() {
    if($('#camera').is(':checked')) {
    $('#map_canvas').show('slow');
   //document.getElementById('map_canvas').style.display = 'block';
    } else {
	$('#map_canvas').hide('slow');
    //document.getElementById('map_canvas').style.display = 'none';
    }
    
}

var t;

$(document).ready(function(){
    $("#search_check_categories").bind("mouseenter",function(){
      clearTimeout(t);
    }).bind("mouseleave",function(){
      t=setTimeout("$('#search_check_categories').slideUp('slow')", 500);
    });

    $("#parent_categories_check").bind("mouseenter",function(){
      clearTimeout(t);
    }).bind("mouseleave",function(){
        t=setTimeout("$('#parent_categories_check').slideUp('slow')", 500);
    });

    $("#parent_subcategory_check").bind("mouseenter",function(){
      clearTimeout(t);
    }).bind("mouseleave",function(){
        t=setTimeout("$('#parent_subcategory_check').slideUp('slow')", 500);
    });

    $("#city_listing").bind("mouseenter",function(){
      clearTimeout(t);
    }).bind("mouseleave",function(){
        t=setTimeout("$('#city_listing').slideUp('slow'); CityListArrow();", 500);
    });

    $("#search_words").bind("mouseenter",function(){
      clearTimeout(t);
    }).bind("mouseleave",function(){
        t=setTimeout("$('#search_words').slideUp('slow');", 500);
    });
});

/* przeniesione z javascript_app.php */

 var  retValue = true;

function odbierzDane()
{
  if (r.readyState == 4) {
    if (r.status == 200 || r.status == 304) {

        e.innerHTML = r.responseText;
    }
  }
}

//AJAX//
function getXMLHttpRequest()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}


function SetTimeClose(elemName) {
    try {
        var ref = $('#'+elemName);
        var ref2 = document.getElementById(elemName);
        setTimeout(function() { if(ref2.style.display == 'block') {
            ref.slideUp();
            CityListArrowDown();
        } }, 3000);
    } catch(elEx) {
    }
}

function CityListArrow() {
    var isVisible = $('#city_listing').css('display');
    if(isVisible=='none') {
        document.getElementById('city_list_arrow').src = urlBase+'application/themes/default/images/purple_up_strzalka.jpg';
    }
    else {
        document.getElementById('city_list_arrow').src = urlBase+'application/themes/default/images/purple_down_strzalka.png';
    }
}

function CityListArrowDown() {
    document.getElementById('city_list_arrow').src = urlBase+'application/themes/default/images/purple_down_strzalka.png';
}

function RightArrow(id, arrow) {
    var isVisible = $('#'+id).css('display');
    if(isVisible=='none') {
        document.getElementById(arrow).src = urlBase+'application/themes/default/images/icon_strzalka_up.png';
    }
    else {
        document.getElementById(arrow).src = urlBase+'application/themes/default/images/icon_strzalka_down.jpg';
    }
}



function CheckCatName2(id, catId, catName) {
    document.getElementById('category_name').innerHTML = catName;
    $('#parent_categories_check').slideToggle('slow');
}

function CheckCatName3(id, catId, catName) {
    document.getElementById('subcategory_name').innerHTML = catName;
    $('#parent_subcategory_check').slideToggle('slow');

}

function SearchUsers(last_name, email, user_status) {
    if (r = getXMLHttpRequest()) {
        e = document.getElementById('users_table');
        r.open('GET', urlBase+"admin_users/ajax_search_users/?last_name="+last_name+"&email="+email+"&user_status="+user_status);
        r.onreadystatechange = odbierzDane;
        r.send(null);
    }
}


function ShowNote(id, AnnNumber, elId) {
    for(i = 1; i<=id; i++) {
	document.getElementById(elId+'_'+i+'_'+AnnNumber).src = urlBase+'application/themes/default/images/mark_full.png';
    }
    while(i<=5) {
	document.getElementById(elId+'_'+i+'_'+AnnNumber).src = urlBase+'application/themes/default/images/mark_empty.png';
	i++;
    }
}

function BackNote(id, AnnNumber, elId) {
    for(i = 1; i<=id; i++) {
	document.getElementById(elId+'_'+i+'_'+AnnNumber).src = urlBase+'application/themes/default/images/mark_full.png';
    }
    while(i<=5) {
	document.getElementById(elId+'_'+i+'_'+AnnNumber).src = urlBase+'application/themes/default/images/mark_empty.png';
	i++;
    }
}

$(function() {
    //set effect from select menu value
    $("#last_add_head").click(function() {
	$("#last_add").toggle('blind','',500, RightArrow('last_add','last_add_arrow'));
	return false;
    });

    $("#right_advert_head").click(function() {
        $("#right_advert").slideToggle('blind','',500, RightArrow('right_advert', 'right_advert_arrow'));
        return false;
    });

    $("#most_search_tag_head").click(function() {
	$("#most_search_tag").toggle('blind','',500, RightArrow('most_search_tag','most_search_tag_arrow'));
	return false;
    });

    $("#right_categories_head").click(function() {
	$("#right_categories").toggle('blind','',500, RightArrow('right_categories','right_categories_arrow'));
	return false;
    });

    $("#right_ann_show_head").click(function() {
	$("#right_ann_show").toggle('blind','',500, RightArrow('right_ann_show', 'right_ann_show'));
	return false;
    });

    $("#right_localization_head").click(function() {
	$("#right_localization").toggle('blind','',500, RightArrow('right_localization', 'right_localization_arrow'));
	return false;
    });

    $("#right_statistic_head").click(function() {
	$("#right_statistic").toggle('blind','',500, RightArrow('right_statistic', 'right_statistic_arrow'));
	return false;
    });

    $("#right_advert_head_wide").click(function() {
	$("#right_advert_wide").toggle('blind','',500, RightArrow('right_advert_wide', 'right_advert_wide'));
	return false;
    });

    $("#right_message_wide_head").click(function() {
	$("#right_message_wide").toggle('blind','',500, RightArrow('right_message_wide', 'right_message_wide_arrow'));
	return false;
    });
});

/**
 * Otwiera okno logowania
 */
function ShowMessage(id) {
        $.ajax({
           type: "GET",
           async: true,
           data: "id="+id,
           url: urlBase+"ajax/message_view/",
           success: function(msg){
                $("#message_view").html(msg);
                $("input:checked").attr("checked", '');
                $("#checkbox_"+id).attr("checked", 'checked');
                setTimeout("MsgRead("+id+")", 5000);
           }
           });

}

function ShowMessage2(id) { // dla wyslanych (nie zaznacza jako przeczytane)
    try {
	if (r = getXMLHttpRequest()) {
	    e = document.getElementById('message_view');
	    r.open('GET', urlBase+"ajax/message_view2/?id="+id);
	    r.onreadystatechange = odbierzDane;
	    r.send(null);

	    //setTimeout("MsgRead("+id+")", 5000);

	}
    }
    catch(e) {

    }
}

function CheckSearchCategories() {
	   $.ajax({
           type: "GET",
	   async: false,
           url: urlBase+"ajax/ddl_categories",
           success: function(msg){
                $("#search_check_categories").html(msg);

           }
           });

	   $('#search_check_categories').slideToggle('slow');

}

function ShowCatsBreadcrumb() {
	   $.ajax({
           type: "GET",
           async: false,
           url: urlBase+"ajax/ddl_categories2",
           success: function(msg){
                $("#parent_categories_check").html(msg);
           }
           });

	   $('#parent_categories_check').slideToggle('slow');
}



function ShowSubcatsBreadcrumb() {
	   $.ajax({
           type: "GET",
           async: false,
           url: urlBase+"ajax/ddl_subcategories2",
           success: function(msg){
                $("#parent_subcategory_check").html(msg);
           }
           });

	   $('#parent_subcategory_check').slideToggle('slow');
}

function SearchWords(search_word)
        {
           $.ajax({
           type: "POST",
           url: urlBase+"ajax/search_words",
           data: "word="+search_word,
           success: function(msg){
                $("#search_words").html(msg);

           }
           });
	   //setCookie('search_word'+search_word,search_word,365);
        setCookie('search_word',search_word,365);
	   $('#search_words').show('slow');

}

function mapOut() {
    document.getElementById('search_results_map').src = urlBase+'application/themes/default/images/search_results_map.jpg';
}

function mapOver(img) {
    document.getElementById('search_results_map').src = urlBase+'application/themes/default/images/'+img;
}

function FindCamera() {
		$.ajax({
			type: "GET",
			async: false,
            url: urlBase+"ajax/find_camera",
			data: "position="+$('#checked_position').val(),
            success: function(msg){
			$("#camera_info").show('slow');
                $("#camera_info").html(msg);

            }
        });
}

function getSubcategorieName(catId) {
    var dataString = 'category_id=' + catId;
    $.ajax({
        type: "POST",
        url: urlBase+"ajax/subcategory_name",
        data: dataString,
        async: false,
        success: function(serverResponse) {
        $('#subcategory_name').html(serverResponse);
        }
    });
}

function getSubcategories2(catId) {
    var dataString = 'category_id=' + catId;
    $.ajax({
        type: "POST",
        url: urlBase+"ajax/ddl_subcategories2",
        data: dataString,
        async: false,
        success: function(serverResponse) {
        $('#parent_subcategory_check').html(serverResponse);
        }
    });
}


function getSubcategories() {
    var dataString = 'category_id=' + $('#category_id').val();
    $.ajax({
        type: "POST",
        url: urlBase+"ajax/get_subcategories",
        data: dataString,
        async: false,
        success: function(serverResponse) {
            var subcat = serverResponse.getElementsByTagName('subcategories');
            var mainElement = serverResponse.getElementsByTagName('category_name');
            for(i = 0 ; i < mainElement.length ; ++i) {
                var cid = mainElement[i].getAttribute('category_id');
                var cname = mainElement[i].firstChild.nodeValue;
                $('#subcategory_id').append('<option value="'+cid+'">'+cname+'</option>');
            }
        },
        error: function(data, status, e) {}
    });
    return retValue;
}

function ChangeNote(note, id, id_name) {
    if (r = getXMLHttpRequest()) {
	r.open('GET', urlBase+"ajax/change_note/?id="+id);
	r.onreadystatechange = function()
	{
	//alert(r.readyState);
	  if (r.readyState == 4) {
	  //alert(r.readyState);
	    if (r.status == 200 || r.status == 304) {
		//alert(r.status);
		document.getElementById('ann_list_'+id).innerHTML = r.responseText;


		var new_note = parseInt(r.responseText);
		for(var i=1; i<=5; i++) {
		    if(i<=new_note) {
		    document.getElementById('ann_list_note_'+i+'_'+id).src = urlBase+'application/themes/default/images/mark_full.png';
		    }
		    else {
		    document.getElementById('ann_list_note_'+i+'_'+id).src = urlBase+'application/themes/default/images/mark_empty.png';
		    }

		    $("#ann_list_note_"+i+"_"+id).parent().removeAttr("onmouseover");



		    //alert('ann_list_note_'+i+'_'+id);
		}
		$("#vote_"+id).removeAttr("onmouseout");
	    }
	  }
	};
	r.send(null);

    }
}

function CheckMsgEmail(email) {
    if (r = getXMLHttpRequest()) {
        e = document.getElementById('email_check');
        r.open('GET', urlBase+"ajax/check_email/?email="+email);
        r.onreadystatechange = odbierzDane;
        r.send(null);
    }
}


function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function PassRepeat2(pass, pass_repeat) {
    if(pass==pass_repeat) {
        document.getElementById('repeat_password_check').innerHTML = '<img src="'+urlBase+'application/themes/default/images/tick.png" alt="tick" />';
    } else {
        document.getElementById('repeat_password_check').innerHTML = '<img src="'+urlBase+'application/themes/default/images/cross.png" alt="cross" />';
    }
}

function PassRepeat(pass, pass_repeat) {
    if(pass==pass_repeat) {
        return true;
    }
    return false;
}

$(document).ready(function() {
    $('#city_id').click(function () {
        $('#city_listing').slideToggle('slow', CityListArrow());
    });

    $('#logout_desc').click(function() {
        FBlogout();
    });

    $('#your_nick').click(function() {
        $('#log_in').show();
    });

    $('#city_list_arrow').click(function() {
        $('#city_listing').slideToggle('slow', CityListArrow());
    });

    $('#city_name').click(function() {
        $('#city_listing').slideToggle('slow', CityListArrow());
    });

    $('#subcategory_name').click(function() {
        $('#parent_subcategory_check').slideToggle('slow');
    });

    $('#rules_show_popup').click(function() {
        regulationPopUp();
    });

    $('.rules').click(function() {
        regulationPopUp();
    });

    $('#add_file_input').click(function() {
        addFileInput();
    });

    $('#check_categories #category_name').click(function() {
        ShowCatsBreadcrumb();
        $('#parent_subcategory_check').slideUp('slow');
    });

    $('#find_camera').click(function() {
        FindCamera();
    });

    $('#fb_auth_cancel').click(function() {
        $('#facebook_auth').css('display', 'none');
        //setCookie('noFB_auth', '1', 360);
    })

    $('#fb_auth_cancel2').click(function() {
        $('#facebook_auth').css('display', 'none');
        //setCookie('noFB_auth', '1', 360);
    })

    $('#right_send_msg').click(function() {
        if(validateMessage()==true) { processCaptcha(); }
    });

    $('#right_send_msg2').click(function() {
        if(validateMessage()==true) { processCaptcha(); }
    });

    $('#yt_upload_form_submit').click(function() {
         if(validateYTupload()) {
             $('#direct_submit').submit();
         } else {
             return false;
         }
    });

    $('#facebook_connect_button').click(function() {
        FB.Connect.requireSession(function() {
            FB.Connect.showPermissionDialog(
            "publish_stream", function() {
                setCookie('fbRegister', true, 1);
                location.href = urlBase;
            });

        });
    });

    $('div[id^=tr_catid]').mouseover(function() {
        $(this).css('backgroundColor', '#e6f8ff');
    });

    $('div[id^=tr_catid]').mouseout(function() {
        $(this).css('backgroundColor', '#ffffff');
    });

    $('[id^="edit_city_id"]').click(function() {
        //alert($(this).attr('title'));
        var title = $(this).attr('title');
        var id = title.split('_');
        $('#edit_ann_city_id').val(id[1]);
        $('#edit_city_check').slideToggle('slow');
        $('#ann_edit_city_check').html(id[0]);
        initialize2(id[0]);
    });
    
});