var username_delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();


jQuery(document).ready(function($) {
    
    try {
    	$(".tipbox").tipbox(0);
    } catch (e) {}
        
    try {
    	$('textarea.expanding').autogrow({
        maxHeight: 300,
        minHeight: 30,
        lineHeight: 30
    	});
	} catch (e) {}
	
    try { 
        $('A[rel="louistab"]').click(function(document){
        /*$('A[rel="louistab"]').live('click', function(document){*/
            $('A[rel="louistab"]').removeAttr('class')
            $(this).attr('class', 'tabFirst curvyTop')
            document.location = location.href + '#' + $(this).attr('href');
            $('.louistabbox:first').load($(this).attr('href')+'?ajax=1');
            return false
        });

    } catch (error) {}

    try { 
        $('.checkUsername').keyup(function(document){
        	encoded_url = php_urlencode($(this).val());
            username_delay(function(){
      			$('.checkUsernameBox').load('/ajax/check_username/?u='+encoded_url);
    		}, 300);
            return false;
        });
    } catch (error) {}

    try {
    	$('.checkUsername').blur(function(document){
	        encoded_url = php_urlencode($(this).val());
	        username_delay(function(){
	            $('.checkUsernameBox').load('/ajax/check_username/?u='+encoded_url);
	        }, 200);
	        return false;
	    });
    } catch (error) {}

    
    try {
        $('A[rel="filter_paginate"]').live('click', function(document){
            $('.filterbox').load($(this).attr('href')+'&ajax=1');
            //$("#contentArea").load($(this).attr('href')+" #contentArea");
            return false
        }); 
    } catch (error) {}

    try {
        $('A[rel="filtertab"]').live('click', function(document){
            $('A[rel="filtertab"]').removeAttr('class')
            $(this).attr('class', 'tabFirst curvyTop')
            
            new_href = $(this).attr('href');
            
            if (new_href.indexOf("?")==-1){
	        	target=new_href+'?ajax=1';
	        } else {
	        	target=new_href+'&ajax=1';
	        }
            
            $('.filterbox').load(target);
            //$("#contentArea").load($(this).attr('href')+" #contentArea");
            return false
        }); 
    } catch (error) {}
    
    try {
        $('A[rel="unblock_user"]').live('click', function(document){
            $('.unblock_users').load($(this).attr('href'));
            return false
        }); 
    } catch (error) {}
    
    $('.cinefile_login_form').live('submit', function(){
        var options = { 
            success: function showResponse(responseText, statusText)  { 
                if (responseText == 'error'){
                    $('#login_errors').html('Invalid username or password');
                    setTimeout(function(){ $("#login_errors").html('Please try again') }, 2000);
                    return false;
                }
                else {
                    document.location = responseText;
                }
            } 
        }; 
        $(this).attr('action',$(this).attr('action')+'&ajax=1');
        $(this).ajaxSubmit(options);
        return false;
    });
    
  	try { 
  		$('.oembed_thumbnail_link').live('click', function(){
            new_href = $(this).attr('href');
            
            if (new_href.indexOf("?")==-1){
	        	target=new_href+'?ajax=1';
	        } else {
	        	target=new_href+'&ajax=1';
	        }
  			try {
  				$(this).hide().next().load(target, function() {
	                                $(this).prepend('<a class="oembed-close" href="#">close</a>');
					$(this).children('.oembed-close').click(function() {
        	        	                $(this).parent().empty().prev().show();
       			                        return false;			
                        	        });
   				});
  			} catch (error) {}
  			
  			return false;
  		});
  		
  	} catch (error) {}

    try { $('a.flyout').flyout({outSpeed: 200, inSpeed: 100}); } catch (error) {}
    try { $('.facebox').boxy(); } catch (error) {}
    try { $('.close').click(function() { $(this).fadeOut("slow"); }); } catch (error) {}

	$('.ajaxLink').live('click', function(){
        var new_href = $(this).attr('href');
        var params = {ajax: 1}
        var rel_id = $(this).attr('rel');
        var ajax_method = $(this).attr('ajax_method'); 
        
        
        if (new_href.indexOf("?")==-1){
        	var target=new_href;
        } else {
        	var target=new_href;
        	var a = new_href.split('?');
        	target = a[0];
        	qs = a[1];
        	var b = qs.split('&');
        	$.each(b, function(x,y){
		  		var temp = y.split('=');
		    	params[temp[0]] = temp[1];
			});
        }
        
        
		$.get(target, params, function(data){
				
				  
				 
				if (!rel_id){ rel_id = $(this).parent(); ajax_method = 'replace'; } 
				
				
	        	if (ajax_method == 'prepend') {
	            	$(rel_id).prepend(data);
	            }
	        	else if (ajax_method == 'append') {
	            	$(rel_id).append(data);
	            }
	        	else if (ajax_method == 'replace') {
	        		
	        		$(rel_id).fadeOut('fast', function(){
	        			$(rel_id).html(data).css('height', 'auto').fadeIn();
	        		})
	        		
	        	}
	        	else if (ajax_method == 'notice') {
				 	try {
				 		$.noticeAdd({text: data, stay: false});
				 	} catch(e) {}
	        	}
	        	else {
	            	$(rel_id).slideUp().end().html();
	            }
					
				
				
				return false;
			});
		return false;
		
		
	});

	$('.ajaxForm').live('submit', function(){
		
		file_selected = new Boolean($(this).find("input:file[value!='']").val());
				
		if (file_selected==true) {
			return true;
		}
		
		var rel = $(this).attr('rel');
        var ajax_method = $(this).attr('ajax_method');
        var clear_text = $(this).attr('clear_text');
        
        var options = {
            success: function showResponse(responseText, statusText)  { 
	        	if (ajax_method == 'prepend') {
	            	$(rel).prepend(responseText);
	            }
	        	else if (ajax_method == 'append') {
	            	$(rel).append(responseText);
	            }
	        	else {
	            	$(rel).html(responseText);
	            	$(rel).css('height', 'auto');
	            }
	        	
	        	if (clear_text){$(clear_text).val('');}
	        	
        	},
        	error: function(arg1, arg2, ex) {alert('error');}
        };
        
        
        new_href = $(this).attr('action');
        if (new_href.indexOf("?")==-1){
        	var target=new_href+'?ajax=1';
        } else {
        	var target=new_href+'&ajax=1';
        }
        
        if (ajax_method != 'append' && ajax_method != 'prepend'){
        	var tmp_height = $(rel).height() + $('#loading_box').height();
        	$(rel).css('height', tmp_height + 'px');
        	$(rel).html($('#loading_box').html());
        }
        
        $(this).attr('action', target);
        try {
        	$(this).ajaxSubmit(options);
        } catch(e) { alert(e); }
        
        var post_submit = $(this).attr('post_submit');
        if (post_submit=='hide_parent'){
        	$(this).parent().slideUp();
        }
        
        return false;

	});
	
	$('.toggleHeight').click(function(){
		var obj_id = $(this).attr('href');
		var original_height = $(this).attr('original_height');
		
		if ($(obj_id).height() == original_height){
			$(obj_id).css('height','auto');
			newHeight = $(obj_id).height();
			$(obj_id).css('height', original_height + 'px');
			$(obj_id).animate( {height: newHeight +'px'}, { queue:false, duration:500 } );
			$(this).text('View Less');
		} else {
			$(obj_id).animate( {height: original_height +'px'}, { queue:false, duration:500 } );
			$(this).text('View More');
		}
		return false;
		
	});
	
	
	$('.commentDetails').mouseenter(function(){
		$(this).children('.commentControls').css("visibility", "visible");
	}).mouseleave(function(){
		$(this).children('.commentControls').css("visibility", "hidden");
	});

	$('.activityPost').mouseenter(function(){
		$(this).find('.x_delete').css("visibility", "visible");
	}).mouseleave(function(){
		$(this).find('.x_delete').css("visibility", "hidden");
	});
	
});

function showCoords(c)
{
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#x2').val(c.x2);
    $('#y2').val(c.y2);
    $('#w').val(c.w);
    $('#h').val(c.h);
}

function clearText(thefield){
    if (thefield.defaultValue==thefield.value)
    thefield.value = "";
}

var SHARE_ICONS = '<a target="_blank" href="http://www.facebook.com/share.php?u=#U#" id="facebook"><img src="/static/images/social_icons/facebook_32.png" alt="facebook" /></a>'+
    '<a target="_blank" href="http://twitter.com/home?status=#U#" id="twitter"><img src="/static/images/social_icons/twitter_32.png" alt="twitter" /></a>'+
    '<a target="_blank" href="http://www.myspace.com/index.cfm?fuseaction=postto&t=#T#&c=#C#&u=#U#" id="myspace"><img src="/static/images/social_icons/myspace_32.png" alt="myspace" /></a>'+
    '<a target="_blank" href="http://digg.com/submit?phase=2&amp;url=#U#&amp;title=#T#&amp;bodytext=" id="digg"><img src="/static/images/social_icons/digg_32.png" alt="digg" /></a>'+
    '<a target="_blank" href="http://reddit.com/submit?url=#U#&amp;title=#T#" id="reddit"><img src="/static/images/social_icons/reddit_32.png" alt="reddit" /></a>'+
    '<a target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&bkmk=#U#&title=#T#&annotation=#C#"><img src="/static/images/social_icons/google_32.png" alt="google" /></a>'+
    '<a target="_blank" href="http://friendfeed.com?url=#U#&amp;title=#T#" id="friendfeed"><img src="/static/images/social_icons/friendfeed_32.png" alt="friendfeed" /></a>'+
    '<a target="_blank" href="http://www.blogger.com/blog_this.pyra?t=#C#&u=#U#&n=#T#"><img src="/static/images/social_icons/blogger_32.png" alt="blogger" /></a>'+
    '<a target="_blank" href="http://www.stumbleupon.com/submit?url=#U#&amp;title=#T#" id="stumbleupon"><img src="/static/images/social_icons/stumbleupon_32.png" alt="stumbleupon" /></a>'+
    '<a target="_blank" href="httsdfp://www.linkedin.com/shareArticle?mini=true&url=#U#&title=#T#&summary=#C#" id="linkedin"><img src="/static/images/social_icons/linkedin_32.png" alt="linkedin" /></a>'+
    '<a target="_blank" href="http://del.icio.us/save?v=5&amp;noui&amp;jump=close&amp;url=#U#&amp;title=#T#" id="delicious"><img src="/static/images/social_icons/delicious_32.png" alt="delicious" /></a>'+
    '<a class="facebox" href="/ajax/share/?url=#U#&title=#T#&snippet=#C#" id="email"><img src="/static/images/social_icons/email_32.png" alt="email" /></a>'

var SHARE_SMALL_ICONS = '<a target="_blank" href="http://www.facebook.com/share.php?u=#U#" id="facebook"><img src="/static/images/1x1.png" alt="" class="small_share facebook" /></a> ' +
    '<a target="_blank" href="http://twitter.com/home?status=#U#" id="twitter"><img src="/static/images/1x1.png" alt="" class="small_share twitter" /></a> ' +
    '<a target="_blank" href="http://www.myspace.com/index.cfm?fuseaction=postto&t=#T#&c=#C#&u=#U#" id="myspace"><img src="/static/images/1x1.png" alt="" class="small_share myspace" /></a> ' +
    '<a target="_blank" href="http://digg.com/submit?phase=2&amp;url=#U#&amp;title=#T#&amp;bodytext=" id="digg"><img src="/static/images/1x1.png" alt="" class="small_share digg" /></a> '+
    '<a target="_blank" href="http://reddit.com/submit?url=#U#&amp;title=#T#" id="reddit"><img src="/static/images/1x1.png" alt="" class="small_share reddit" /></a> '+
    '<a target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&bkmk=#U#&title=#T#&annotation=#C#"><img src="/static/images/1x1.png" alt="" class="small_share google" /></a> '+
    '<a target="_blank" href="http://friendfeed.com?url=#U#&amp;title=#T#" id="friendfeed"><img src="/static/images/1x1.png" alt="" class="small_share friendfeed" /></a> '+
    '<a target="_blank" href="http://www.blogger.com/blog_this.pyra?t=#C#&u=#U#&n=#T#"><img src="/static/images/1x1.png" alt="" class="small_share blogger" /></a> '+
    '<a target="_blank" href="http://www.stumbleupon.com/submit?url=#U#&amp;title=#T#" id="stumbleupon"><img src="/static/images/1x1.png" alt="" class="small_share stumbleupon" /></a> '+
    '<a target="_blank" href="http://del.icio.us/save?v=5&amp;noui&amp;jump=close&amp;url=#U#&amp;title=#T#" id="delicious"><img src="/static/images/1x1.png" alt="" class="small_share delicious" /></a> '+
    '<a class="facebox" title="Email a Friend" href="/ajax/share/?url=#U#&title=#T#&snippet=#C#" id="email"><img src="/static/images/1x1.png" alt="" class="small_share email" /></a>'

function php_urlencode(str) {
    str = escape(str);
    return str.replace(/[*+\/@]|%20/g,
    function (s) {
        switch (s) {
        case "*": s = "%2A"; break;
        case "+": s = "%2B"; break;
        case "/": s = "%2F"; break;
        case "@": s = "%40"; break;
        case "%20": s = "+"; break;
        }
        return s;
    });
}

function rebuild_share(url, title, description, target){
	var re = new RegExp('^http://');
	if (!url.match(re)) {
	    url = 'http://'+document.domain+url;
	}
	
	h = SHARE_ICONS;
    h=h.replace(/#U#/g, php_urlencode(url));
    h=h.replace(/#T#/g, php_urlencode(title));
    h=h.replace(/#C#/g, php_urlencode(description));
    $(target).html(h);
}

function rebuild_small_share(url, title, description, target){
	var re = new RegExp('^http://');
	if (!url.match(re)) {
	    url = 'http://'+document.domain+url;
	}
	
	
	h = SHARE_SMALL_ICONS;
    h=h.replace(/#U#/g, php_urlencode(url));
    h=h.replace(/#T#/g, php_urlencode(title));
    h=h.replace(/#C#/g, php_urlencode(description));
    $(target).html(h);
}

function doLogin(return_to){
		if (return_to == '/account/logout/') {
			return_to = '/account/';
		}
		return_to = php_urlencode(return_to);
        Boxy.load('/account/login/?ajax=1&next='+return_to, options={
        	'cache':true, 
        	'modal': true, 
        	'title': false,
        	'afterShow': function(){ $('#id_username').focus(); }
        	});
        return false;
}

function checkLogin(link, requires_login){
    if (requires_login==true && logged_in==false){
		this_url = $(link).attr('href');
		doLogin(this_url);
		return false;
    } else {
        return true;
    }
    
}

function cloneMore(selector, type) {
    var newElement = $(selector).clone();
    var total = $('#id_' + type + '-TOTAL_FORMS').val();
    var max_num = $('#id_' + type + '-MAX_NUM').html();
    if (!max_num){max_num=1000;}
	var current_count = $(selector).siblings('li').length+1; // +1 for 0 index
	
    if (current_count < max_num) {
    
	    newElement.find(':input').each(function() {
	        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
	        var id = 'id_' + name;
	        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
	    });
	    newElement.find('label').each(function() {
	        var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
	        $(this).attr('for', newFor);
	    });
	    total++;
	    $('#id_' + type + '-TOTAL_FORMS').val(total);
	    $(selector).after(newElement);
	    
	    if (current_count+1==max_num) {
	    	$(selector).find('a.extend-formset').fadeOut();
	    }
	    
    } else {}
    
    return false;

}

function clickConfirm(message){
	var confirmed = false;
	Boxy.confirm(message, function(){ confirmed=true; return false; });
	// alert(confirmed); 
	return false;
}

function html_entity_decode(string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Ratheous
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Nick Kolosov (http://sammy.ru)
    // +   bugfixed by: Fox
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'

    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // fix &amp; problem
    // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
    delete(hash_map['&']);
    hash_map['&'] = '&amp;';

    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}

