if(typeof(String.prototype.trim) === "undefined")
{
    String.prototype.trim = function() {
        var str = String(this).replace(/^\s\s*/, ''),
            ws = /\s/,
            i = str.length;
        while (ws.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    };
}

jQuery.fn.autoscroll = function() {
    $('html,body').animate({scrollTop: this.offset().top}, 500);
}
$(function() {
    var profile_avatar = $('#profile_avatar');
    if(profile_avatar) {
        profile_avatar.bind('mouseenter', function() {
            $('#avatar_replace').css('display', 'block');
        }).bind('mouseleave', function() {
            $('#avatar_replace').css('display', 'none');
        });
    }
    var ymap = document.getElementById('ymap');
    if(ymap) {
        var map = new YMap(ymap);
        // Add map type control  
        map.addTypeControl();  
        // Add map zoom (long) control  
        map.addZoomLong();  
        // Add the Pan Control  
        map.addPanControl();
        for(var i = 0; i < _geo.length; ++i) {
            var g = _geo[i];
            var yPoint = new YGeoPoint(g[0], g[1]);
            // Display the map centered on a geocoded location
            map.drawZoomAndCenter(yPoint, 12);
            // Create a new marker for an address
            var myMarker = new YMarker(yPoint);
            // Create some content to go inside the SmartWindow
            var myMarkerContent = g[2];
            // When the marker is clicked, show the SmartWindow
            YEvent.Capture(myMarker, EventsList.MouseClick, function() {
                myMarker.openSmartWindow(myMarkerContent); 
            });
            // Put the marker on the map
            map.addOverlay(myMarker);
            var pageLink = document.getElementById('loc_' + i);
            if(pageLink) {
                pageLink.onclick = function() {
                    var geoIndex = parseInt(this.id.replace('loc_', ''), 10);
                    var g = _geo[geoIndex];
                    var yPoint = new YGeoPoint(g[0], g[1]);
                    map.drawZoomAndCenter(yPoint, 12);
                };
            }
        }
    }
});

$(function() {
	// Helper functions to feel DRY
    function hideFlowPlayer() {
        if (typeof(flowplayer) == 'function') {
            $f().hide().pause();
        }
	};
    function showFlowPlayer(){
		if (typeof(flowplayer) == 'function') {
			$f().show().resume();
		}
	};

	// Setting up overlays
    $('.overlay').overlay({
        expose: { 
            color: '#333', 
            loadSpeed: 200, 
            opacity: 0.9,
            zIndex: 5
        },
        top: 'center',
        onBeforeLoad: hideFlowPlayer,
        onClose: showFlowPlayer
    });
	
    // Adding handlers to edit-form(s)
    $('#edit-form').submit(function(e) {
		e.preventDefault();

        var form = $(this);

        $.post(form.attr('action'), form.serialize(), function(data) {
            if (data.status == 'ok') {
                window.location.replace(data.url);
			} else {
				$('.errorlist').remove();
				if (data.non_field_errors) {
                    var error_list = $('<ul />').attr('class', 'errorlist');
                    for (error in data.non_field_errors) {
                        error_list.append($('<li></li>').html(data.non_field_errors[error]));
                    }
					form.append(error_list);
				}
				if (data.errors) {
					for (field in data.errors) {
                        var error_list = $('<ul />').attr('class', 'errorlist');
                        for (error in data.errors[field]) {
                            error_list.append($('<li></li>').html(data.errors[field][error]));
                        }
                        $('#id_' + field).before(error_list);
					}
                }
			}
		}, 'json');
	});

    // Adding "loading" popup windows for video and photo upload forms
	$('#photo_form').submit(function(e) {
        $('div.modal').overlay({
            expose: { 
                color: '#333', 
                loadSpeed: 200, 
                opacity: 0.9
            },
            top: 'center',
            api: true,
            close: true,
            closeOnClick: false
         }).load();
    });
	
    // Adding rating button hooks
    $('div.voting-results a').each(function(){
        var obj = $(this);
        var url = obj.attr('href');
        
        obj.click(function(e){
            e.preventDefault();
            $.getJSON(url, {}, function(data){ // we don't check for rating errors yet
                if (data.code == 200) {
////                    var rating = $('<div class="sprite rating-button-big"></div>');
////                    rating.attr('title', data.value).addClass('bigrating' + parseInt(data.value));
////                    $($('button.rating-change-button')[0]).replaceWith(rating);
                    // Set voices count; set bar heights; remove "rate me" text
                }
                $('div.voting-results').remove();
            });
        });
    });

    $('.close').click(function () {
        $('.modal').close();
        return false;
    });

	// Setting rollover
	$('.video_thumb img').rollover();

    $('.toggle_element').click(function(e) {
        element_name = $(this).get(0).rel;
        $(element_name).slideToggle('slow');
        $(element_name).autoscroll();
        return false;
    });
});

function putErrors(form, non_field_errors, errors) {
	$('.errorlist').remove();
	if (non_field_errors) {
        var error_list = $('<ul />').attr('class', 'errorlist');
        for (error in non_field_errors) {
            error_list.append($('<li></li>').html(non_field_errors[error]));
        }
        form.append(error_list);
	}
	if (errors) {
		for (field in errors) {
			var error_list = $('<ul />').attr('class', 'errorlist');
			for (error in errors[field]) {
				error_list.append($('<li></li>').html(errors[field][error]));
			}
			$('#id_' + field).before(error_list);
		}
	}
}

// Rollover plugin
(function($){
    $.fn.extend({
        rollover: function() {
            return this.each(function() {
				var el = $(this);
				var base_url = el.attr('src');
				var timer_id = null;
				var image_list = [];

                el.mouseover(function() {
					if (!image_list.length) {
						// Populate imagelist
                        var duration = $(this).parent().parent().find('.duration_in_seconds').val();
                        var images_count = 10;
						image_list.push(new Image());
						image_list[0].src = base_url;
						for (var i = 1; i <= images_count; i++) {
                            var url_parts = base_url.split('.');
							var prelast = url_parts.length - 2;
                            url_parts[prelast] = url_parts[prelast] + '-' + i;
							var img = new Image();
							img.src = url_parts.join('.');
							image_list.push(img);
						}
					}
					
					timer_id = setInterval(function() {
						do {
                            var image = image_list.shift();
						} while (image.complete && image.width == 0);

						el.attr('src', image.src);
						image_list.push(image);
					}, 1000);
                });
				el.mouseout(function() {
                    clearInterval(timer_id);
				});
            });
        }
    });
})(jQuery);



function toggle_comment_form(id){
    var cform = $('#comment_form_' + id);
    if(cform.hasClass('hidden')) {
        cform.prev().text("Stop Replying to This Post");
        cform.slideDown();
    }
    else {
        cform.prev().text("Reply to This Post");
        cform.slideUp();
    }
    cform.toggleClass('hidden');
}


