var GoogleMap;
var GoogleMarker;

function getCoordinatesFromGoogleApi(address, id)
{
	geocoder = new GClientGeocoder();
	
	geocoder.getLatLng(
        address,
        function(point) {
        	if (point) {
        		jQuery('#form_koordynaty').val(point);
        		return point;
        	} else {
        		jQuery('#form_koordynaty').val('');
        	}        
        }
  );
}

function showMarker( id, point )
{
	point = point.replace(/[()]/gi,"");
	point = point.split(',');
	GoogleMap.setCenter(new GLatLng( point[0], point[1] ) );
}

function showGmap( id, point, zoom, input, pointHtml, odniesienie, edit )
{
		point = point.replace(/[()]/gi,"");
		point = point.split(',');
		if ( !odniesienie ) {	odniesienie = 'left';	}
		if ( odniesienie.length == '0' ) {	odniesienie = 'left';		}
		if ( !pointHtml ) {	pointHtml = ''; }
		if ( !input ) {	input = '';	}

		width = (parseInt(document.getElementById( id ).style.width));
		height = parseInt(document.getElementById( id ).style.height);

		if (GBrowserIsCompatible()) {											
			if ( edit == 'true' ) {
				var map = GoogleMap = new GMap2(document.getElementById( id ), { size: new GSize(width, height) } ) ;
			} else {
				var map = new GMap2(document.getElementById( id ), { size: new GSize(width, height) } ) ;
			}
			/* glowne elementy */		
			map.setCenter(new GLatLng( point[0], point[1] ), zoom); 
			map.addControl(new GSmallZoomControl ());
			//map.hideControls();
			GEvent.addListener(map, "mouseover", function(){map.showControls();});   
			GEvent.addListener(map, "mouseout", function(){map.hideControls();});  

			//słuchacze
			if ( input.length != '0' ) {
				input = '#'+input; 
				var marker = GoogleMarker = new GMarker( new GLatLng( point[0], point[1] ), {draggable: true});
	      GEvent.addListener(marker, "dragend", function() {
	              jQuery(input).val( marker.getLatLng() );
	      });
	
	      GEvent.addListener(map,"click",function(overlay, point) {
	              marker.setLatLng(point);
	              jQuery(input).val( marker.getLatLng() );
	      });
	      map.addOverlay(marker);
	      return map;
			}
					
			//znacznik	
      if (  pointHtml.length != '0' ) {
	      function createMarker(map, point, html) {
	        var marker = new GMarker(point);
	        GEvent.addListener(marker, "click", function() {
	          map.openInfoWindowHtml(point, html);
	        });
	        return marker;
	      }
      	map.addOverlay(createMarker(map, new GLatLng( point[0], point[1] ), pointHtml ));
      } else {
      	map.addOverlay(new GMarker( new GLatLng( point[0], point[1] ) ));
      }
  		return map; 	
	  }
}

	function geoLocate( prefix ) {
		if(jQuery("#"+prefix+"_google_miasto").val() == 'miejscowość') {
			var miasto = jQuery("#"+prefix+"_miasto").val()
		} else {
			var miasto = jQuery("#"+prefix+"_google_miasto").val()
		}
		
		if(jQuery("#"+prefix+"_google_ulica").val() == 'ulica') {
			var ulica = ''
		} else {
			var ulica = jQuery("#"+prefix+"_google_ulica").val()
		}
		
		if(jQuery("#"+prefix+"_google_numer").val() == 'numer') {
			var numer = ''
		} else {
			var numer = jQuery("#"+prefix+"_google_numer").val()
		}
		
		var address = miasto + "," + "ul. " + ulica + " " + numer;
		if(address != ',ul.  ') {
			var geocoder = new GClientGeocoder();
			geocoder.getLatLng( address, 
			   function(point) {
			     if(point) {
			       if (GoogleMap) {
			        GoogleMap.setCenter(point, 13);
		  	      GoogleMarker.setLatLng(point);
		    	    GoogleMap.setCenter(point, 13);
			        jQuery('#'+prefix+'_koordynaty').val(point);
			       }
			     }
			   }
			);
		}
	}

function Rate( id, rate )
{
	jQuery("#grades").html('<img src="/images/grades_disabled.png" width="269" height="23" alt="oddałeś już głos" />');
 	jQuery.post("/ciuszekGlosuj",{'id':id,'w':rate} , function(data) {
		if (data.error == '' ) {
			if ( rate > 5 ) {
				if (data.avatar != '') {
					jQuery("#pozytywnie").text( parseInt(jQuery("#pozytywnie").text() )+1 );
				}
				jQuery("#pozytywnie-avatar").append( data.avatar );
			}			
			jQuery("#ocena").html( data.ocena );
			jQuery("#ilosc").html( data.ilosc );
		} else {
			jQuery("#grades").html( data.error );
		}
	}, "json");	
	return false;
}

function EditnOnIbutik ( login, id ) {
    jQuery.post( "/iButikLogin", {},
        function (data, textStatus) {
            window.open("http://test123.ibutik.pl/ajax/zaloguj_kluczem/"+login+"/"+data.login+"/"+id );
        }, "json"
    ); 
}

function ObjectToFav ( id ) {
	jQuery("#button_ObjectToFav").hide();
    jQuery.post( "/przedmiotDoUlubionych", {'id':id }, function (data) {
    	if (data.error == '' ) {
    		jQuery("#ajax_window").html(data.msg);
    		jQuery("#ilosc_ulubione_przedmioty").html(data.ilosc);    		
    	} else {
        	jQuery("#ajax_window").html(data.error);
    	}
    }, "json" );
    return false;
}

function DeleteFav ( id ) {
    jQuery.post( "/przedmiotZUlubionych", {'id':id }, function (data) {
    	if (data.error == '' ) {
    		jQuery("#ajax_window").html(data.msg);
    		jQuery(".fav_"+id).hide();
        	jQuery("#button_DeleteFav").hide();
    		jQuery("#ilosc_ulubione_przedmioty").html(data.ilosc);    		
    	} else {
        	jQuery("#ajax_window").html(data.error);
    	}
    }, "json" );
    return false;
}
    
function VoteComment( id, typ, w, n )
{
	jQuery("#ico_nie_"+id).html( '<span class="i_map i_psnie" title="&darr;">&nbsp;</span>' );
	jQuery("#ico_tak_"+id).html( '<span class="i_map i_pstak" title="&darr;">&nbsp;</span>' );
	if ( n == 'true' ) {
		jQuery("#nico_nie_"+id).html( '<span class="i_map i_psnie" title="&darr;">&nbsp;</span>' );
		jQuery("#nico_tak_"+id).html( '<span class="i_map i_pstak" title="&darr;">&nbsp;</span>' );
	}
	
 	jQuery.post("/komentarzGlosuj",{'id':id,'typ':typ,'w':w} , function(data) { 	
		if (data.error == '' ) {
			jQuery("#p_tak_"+id).text( data.p_tak );
			jQuery("#p_nie_"+id).text( data.p_nie );
			jQuery("#i_tak_"+id).text( data.i_tak );
			jQuery("#i_nie_"+id).text( data.i_nie );
			if ( n == 'true' ) {
				jQuery("#np_tak_"+id).text( data.p_tak );
				jQuery("#np_nie_"+id).text( data.p_nie );
				jQuery("#ni_tak_"+id).text( data.i_tak );
				jQuery("#ni_nie_"+id).text( data.i_nie );
			}
		} else {
			alert( data.error );
		}
	}, "json");	
	return false;
}

function VoteAnswer( id, typ, w, n )
{
	jQuery("#ico_nie_"+id).html( '<span class="i_map i_snie" title="&darr;">&nbsp;</span>' );
	jQuery("#ico_tak_"+id).html( '<span class="i_map i_stak" title="&darr;">&nbsp;</span>' );
	if ( n == 'true' ) {
		jQuery("#nico_nie_"+id).html( '<span class="i_map i_snie" title="&darr;">&nbsp;</span>' );
		jQuery("#nico_tak_"+id).html( '<span class="i_map i_stak" title="&darr;">&nbsp;</span>' );
	}

	jQuery.post("/odpowiedzGlosuj",{'id':id,'typ':typ,'w':w} , function(data) {
		if (data.error == '' ) {
			jQuery("#p_tak_"+id).text( data.p_tak );
			jQuery("#p_nie_"+id).text( data.p_nie );
			jQuery("#i_tak_"+id).text( data.i_tak );
			jQuery("#i_nie_"+id).text( data.i_nie );
			if ( n == 'true' ) {
				jQuery("#np_tak_"+id).html( '<a>Głosuj za</a> ' + data.p_tak + '%');
				
				jQuery("#np_tak_"+id).removeClass("vote-up");
				jQuery("#np_tak_"+id).addClass("novote-up");
				
				jQuery("#np_nie_"+id).html( '<a>Głosuj przeciw</a>' + data.p_nie + '%');
				
				jQuery("#np_nie_"+id).removeClass("vote-down");
				jQuery("#np_nie_"+id).addClass("novote-down");
				
				jQuery("#npp_tak_"+id).text( data.i_tak );
				jQuery("#npp_nie_"+id).text( data.i_nie );

				jQuery("#npi_tak_"+id).html( '<a>Głosuj za</a> ' + data.p_tak + '%');
				
				jQuery("#npi_tak_"+id).removeClass("vote-up");
				jQuery("#npi_tak_"+id).addClass("novote-up");
				
				jQuery("#npi_nie_"+id).html( '<a>Głosuj przeciw</a>' + data.p_nie + '%');
				
				jQuery("#npi_nie_"+id).removeClass("vote-down");
				jQuery("#npi_nie_"+id).addClass("novote-down");
				
				jQuery("#npii_tak_"+id).text( data.i_tak );
				jQuery("#npii_nie_"+id).text( data.i_nie );
			}
		} else {
			alert( data.error );
		}
	}, "json");	
	return false;
}

jQuery(function() {	
	jQuery("#pyt_google_miasto").click( function () { if(jQuery("#pyt_google_miasto").val() == 'miejscowość') { jQuery("#pyt_google_miasto").css('color', 'black'); jQuery("#pyt_google_miasto").attr('value','');} });
	jQuery("#pyt_google_ulica").click( function () { if(jQuery("#pyt_google_ulica").val() == 'ulica') { jQuery("#pyt_google_ulica").css('color', 'black'); jQuery("#pyt_google_ulica").attr('value','');} });
	jQuery("#pyt_google_numer").click( function () { if(jQuery("#pyt_google_numer").val() == 'numer') { jQuery("#pyt_google_numer").css('color', 'black'); jQuery("#pyt_google_numer").attr('value','');} });
	jQuery("#pyt_google_miasto").change( function () { geoLocate('pyt'); } );
	jQuery("#pyt_google_ulica").change( function () { geoLocate('pyt'); } );
	jQuery("#pyt_google_numer").change( function () { geoLocate('pyt'); } );
	
	jQuery("#komentarz_google_miasto").click( function () { if(jQuery("#komentarz_google_miasto").val() == 'miejscowość') { jQuery("#komentarz_google_miasto").css('color', 'black'); jQuery("#komentarz_google_miasto").attr('value','');} });
	jQuery("#komentarz_google_ulica").click( function () { if(jQuery("#komentarz_google_ulica").val() == 'ulica') { jQuery("#komentarz_google_ulica").css('color', 'black'); jQuery("#komentarz_google_ulica").attr('value','');} });
	jQuery("#komentarz_google_numer").click( function () { if(jQuery("#komentarz_google_numer").val() == 'numer') { jQuery("#komentarz_google_numer").css('color', 'black'); jQuery("#komentarz_google_numer").attr('value','');} });
	jQuery("#komentarz_google_miasto").change( function () { geoLocate('komentarz'); } );
	jQuery("#komentarz_google_ulica").change( function () { geoLocate('komentarz'); } );
	jQuery("#komentarz_google_numer").change( function () { geoLocate('komentarz'); } );
	
	jQuery("#form_google_miasto").click( function () { if(jQuery("#form_google_miasto").val() == 'miejscowość') { jQuery("#form_google_miasto").css('color', 'black'); jQuery("#form_google_miasto").attr('value','');} });
	jQuery("#form_google_ulica").click( function () { if(jQuery("#form_google_ulica").val() == 'ulica') { jQuery("#form_google_ulica").css('color', 'black'); jQuery("#form_google_ulica").attr('value','');} });
	jQuery("#form_google_numer").click( function () { if(jQuery("#form_google_numer").val() == 'numer') { jQuery("#form_google_numer").css('color', 'black'); jQuery("#form_google_numer").attr('value','');} });
	jQuery("#form_google_miasto").change( function () { geoLocate('form'); } );
	jQuery("#form_google_ulica").change( function () { geoLocate('form'); } );
	jQuery("#form_google_numer").change( function () { geoLocate('form'); } );
	
    jQuery("#wszystkie").click(function(){
		jQuery("input[type=checkbox]").attr('checked',true);
	});	
	
	jQuery("#zadne").click(function(){
		jQuery("input[type=checkbox]").attr('checked',false);
	});	
		
	jQuery("#nieprzeczytane").click(function(){
  		jQuery(".check_przeczytana").attr('checked',false);
  		jQuery(".check_nieprzeczytana").attr('checked',true);
	});
	
	jQuery("#przeczytane").click(function(){
  		jQuery(".check_przeczytana").attr('checked',true);
  		jQuery(".check_nieprzeczytana").attr('checked',false);
	});
});

/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function(jQuery) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: jQuery("#myTextArea").charCounter(max, settings);
	 */
	
	jQuery.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = jQuery.extend({
			container: "<span></span>",
			classname: "charcounter",
			format: "(%1 characters remaining)",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;
		
		function count(el, container) {
			el = jQuery(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			
			var len = max - el.val().length;
			if ( len == 1  ) {
				outext = 'Pozostał <b class="podpis">1</b> znak.';
			}
			else if ( len % 10 >= 2 && len % 10 <= 4 && (len < 5 || len > 21) ) {
				outext = 'Pozostały <b class="podpis">'+len+'</b> znaki.';
			}
			else {
				outext = 'Pozostało <b class="podpis">'+len+'</b> znaków.';
			}			
			
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(outext);
				}, settings.delay);
			} else {
				container.html(outext);
			}
		};
		
		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				jQuery(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};
		
		return this.each(function () {
			var container = (!settings.container.match(/^<.+>jQuery/)) 
				? jQuery(settings.container) 
				: jQuery(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			jQuery(this)
				.bind("keydown", function () { count(this, container); })
				.bind("keypress", function () { count(this, container); })
				.bind("keyup", function () { count(this, container); })
				.bind("focus", function () { count(this, container); })
				.bind("mouseover", function () { count(this, container); })
				.bind("mouseout", function () { count(this, container); })
				.bind("paste", function () { 
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			};
			count(this, container);
		});
	};

})(jQuery);


/*
  @author: remy sharp / http://remysharp.com
  @url: http://remysharp.com/2007/12/28/jquery-tag-suggestion/
  @usage: setGlobalTags(['javascript', 'jquery', 'java', 'json']); // applied tags to be used for all implementations
          jQuery('input.tags').tagSuggest(options);
          
          The selector is the element that the user enters their tag list
  @params:
    matchClass - class applied to the suggestions, defaults to 'tagMatches'
    tagContainer - the type of element uses to contain the suggestions, defaults to 'span'
    tagWrap - the type of element the suggestions a wrapped in, defaults to 'span'
    sort - boolean to force the sorted order of suggestions, defaults to false
    url - optional url to get suggestions if setGlobalTags isn't used.  Must return array of suggested tags
    tags - optional array of tags specific to this instance of element matches
    delay - optional sets the delay between keyup and the request - can help throttle ajax requests, defaults to zero delay
    separator - optional separator string, defaults to ' ' (Brian J. Cardiff)
  @license: Creative Commons License - ShareAlike http://creativecommons.org/licenses/by-sa/3.0/
  @version: 1.4
  @changes: fixed filtering to ajax hits
*/

(function (jQuery) {
    var globalTags = [];

    // creates a public function within our private code.
    // tags can either be an array of strings OR
    // array of objects containing a 'tag' attribute
    window.setGlobalTags = function(tags /* array */) {
        globalTags = getTags(tags);
    };
    
    function getTags(tags) {
        var tag, i, goodTags = [];
        for (i = 0; i < tags.length; i++) {
            tag = tags[i];
            if (typeof tags[i] == 'object') {
                tag = tags[i].tag;
            } 
            goodTags.push(tag.toLowerCase());
        }
        
        return goodTags;
    }
    
    jQuery.fn.tagSuggest = function (options) {
        var defaults = { 
            'matchClass' : 'tagMatches', 
            'tagContainer' : 'span', 
            'tagWrap' : 'span', 
            'sort' : true,
            'tags' : null,
            'url' : null,
            'delay' : 0,
            'separator' : ' '
        };

        var i, tag, userTags = [], settings = jQuery.extend({}, defaults, options);

        if (settings.tags) {
            userTags = getTags(settings.tags);
        } else {
            userTags = globalTags;
        }

        return this.each(function () {
            var tagsElm = jQuery(this);
            var elm = this;
            var matches, fromTab = false;
            var suggestionsShow = false;
            var workingTags = [];
            var currentTag = {"position": 0, tag: ""};
            var tagMatches = document.createElement(settings.tagContainer);
            
            function showSuggestionsDelayed(el, key) {
                if (settings.delay) {
                    if (elm.timer) clearTimeout(elm.timer);
                    elm.timer = setTimeout(function () {
                        showSuggestions(el, key);
                    }, settings.delay);
                } else {
                    showSuggestions(el, key);
                }
            }

            function showSuggestions(el, key) {
                workingTags = el.value.split(settings.separator);
                matches = [];
                var i, html = '', chosenTags = {}, tagSelected = false;

                // we're looking to complete the tag on currentTag.position (to start with)
                currentTag = { position: currentTags.length-1, tag: '' };
                
                for (i = 0; i < currentTags.length && i < workingTags.length; i++) {
                    if (!tagSelected && 
                        currentTags[i].toLowerCase() != workingTags[i].toLowerCase()) {
                        currentTag = { position: i, tag: workingTags[i].toLowerCase() };
                        tagSelected = true;
                    }
                    // lookup for filtering out chosen tags
                    chosenTags[currentTags[i].toLowerCase()] = true;
                }

                if (currentTag.tag) {
                    // collect potential tags
                    if (settings.url) {
                        jQuery.ajax({
                            'url' : settings.url,
                            'dataType' : 'json',
                            'data' : { 'tag' : currentTag.tag },
                            'async' : false, // wait until this is ajax hit is complete before continue
                            'success' : function (m) {
                                matches = m;
                            }
                        });
                    } else {
                        for (i = 0; i < userTags.length; i++) {
                            if (userTags[i].indexOf(currentTag.tag) === 0) {
                                matches.push(userTags[i]);
                            }
                        }                        
                    }
                    
                    matches = jQuery.grep(matches, function (v, i) {
                        return !chosenTags[v.toLowerCase()];
                    });

                    if (settings.sort) {
                        matches = matches.sort();
                    }                    

                    for (i = 0; i < matches.length; i++) {
                        html += '<' + settings.tagWrap + ' class="_tag_suggestion">' + matches[i] + ',</' + settings.tagWrap + '> ';
                    }

                    tagMatches.html(html);
                    suggestionsShow = !!(matches.length);
                } else {
                    hideSuggestions();
                }
            }

            function hideSuggestions() {
                tagMatches.empty();
                matches = [];
                suggestionsShow = false;
            }

            function setSelection() {
                var v = tagsElm.val();

                // tweak for hintted elements
                // http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
                if (v == tagsElm.attr('title') && tagsElm.is('.hint')) v = '';

                currentTags = v.split(settings.separator);
                hideSuggestions();
            }

            function chooseTag(tag) {
                var i, index;
                for (i = 0; i < currentTags.length; i++) {
                    if (currentTags[i].toLowerCase() != workingTags[i].toLowerCase()) {
                        index = i;
                        break;
                    }
                }

                if (index == workingTags.length - 1) tag = tag + settings.separator;

                workingTags[i] = tag;

                tagsElm.val(workingTags.join(settings.separator));
                tagsElm.blur().focus();
                setSelection();
            }

            function handleKeys(ev) {
                fromTab = false;
                var type = ev.type;
                var resetSelection = false;
                
                switch (ev.keyCode) {
                    case 37: // ignore cases (arrow keys)
                    case 38:
                    case 39:
                    case 40: {
                        hideSuggestions();
                        return true;
                    }
                    case 224:
                    case 17:
                    case 16:
                    case 18: {
                        return true;
                    }

                    case 8: {
                        // delete - hide selections if we're empty
                        if (this.value == '') {
                            hideSuggestions();
                            setSelection();
                            return true;
                        } else {
                            type = 'keyup'; // allow drop through
                            resetSelection = true;
                            showSuggestionsDelayed(this);
                        }
                        break;
                    }

                    case 9: // return and tab
                    case 13: {
                        if (suggestionsShow) {
                            // complete
                            chooseTag(matches[0]);
                            
                            fromTab = true;
                            return false;
                        } else {
                            return true;
                        }
                    }
                    case 27: {
                        hideSuggestions();
                        setSelection();
                        return true;
                    }
                    case 32: {
                        setSelection();
                        return true;
                    }
                }

                if (type == 'keyup') {
                    switch (ev.charCode) {
                        case 9:
                        case 13: {
                            return true;
                        }
                    }

                    if (resetSelection) { 
                        setSelection();
                    }
                    showSuggestionsDelayed(this, ev.charCode);            
                }
            }

            tagsElm.after(tagMatches).keypress(handleKeys).keyup(handleKeys).blur(function () {
                if (fromTab == true || suggestionsShow) { // tweak to support tab selection for Opera & IE
                    fromTab = false;
                    tagsElm.focus();
                }
            });

            // replace with jQuery version
            tagMatches = jQuery(tagMatches).click(function (ev) {
                if (ev.target.nodeName == settings.tagWrap.toUpperCase() && jQuery(ev.target).is('._tag_suggestion')) {
                    chooseTag(ev.target.innerHTML);
                }                
            }).addClass(settings.matchClass);

            // initialise
            setSelection();
        });
    };
})(jQuery);