var actionDone = false;
var photos_path = '/uploaded_photos';

$(document).ready(function() {
    $('#dialog').dialog({
        show: "drop", 
        hide: "drop", 
        modal: true, 
        resizable: false, 
        height: 250, 
        autoOpen: false
    });
    
    $('#user-carousel').show();
    $('#user-carousel').jcarousel({
        auto: 0,
        scroll: 1,
        wrap: 'last'
    });
    
	$('#main_carousel').show();
	$('#home-carousel').jcarousel({
		wrap: 'both',
		scroll: 1,
		auto: 7,
		initCallback: home_carousel_initCallback,
	});
    $('#cotm-voting-carousel').jcarousel({
        auto: 5,
        scroll: 1,
        wrap: 'last',
        initCallback: cotm_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null,
    });
    $('#coty-voting-carousel').jcarousel({
        auto: 5,
        scroll: 1,
        wrap: 'last',
        initCallback: coty_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null,
    });
});

function cotm_initCallback(carousel) {
    $('.controls').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('id').replace('control-', '')));
        carousel.startAuto(0);
        return false;
    });
}

function coty_initCallback(carousel) {
    $('.controls').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('id').replace('control-', '')));
        carousel.startAuto(0);
        return false;
    });
}

var timer_carousel = 0;
function home_carousel_initCallback (carousel) {
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
		clearTimeout(timer_carousel);
		timer_carousel=setTimeout(function(){carousel.startAuto(7)},3000);
	});

	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
		clearTimeout(timer_carousel);
		timer_carousel=setTimeout(function(){carousel.startAuto(7)},3000);
	});

	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		clearTimeout(timer_carousel);
		carousel.stopAuto();
	}, function() {
		carousel.startAuto(7);
	});
};

/*Thumbnail carousel on girl-photo-page starts*/
$(document).ready(function() {
	$('#chick_photo_thumbnails_carousel').jcarousel({
	    wrap: 'circular',
	    scroll: 1
	});
});
/*Thumbnail carousel on girl-photo-page ends*/

/*Thumbnail carousel on girl-video-page starts*/
$(document).ready(function() {
	$('#chick_video_thumbnails_carousel').jcarousel({
	    wrap: 'circular',
	    scroll: 1
	});
});
/*Thumbnail carousel on girl-video-page ends*/

/*Serve for hiding shadowed-overlay*/
function hide_popup () {
	//$('#message-box').css({background:'', border:''});
	$('#message-box').css({'-moz-border-radius' : '', 'border-radius': ''});
	$('#close-button').css({color:'#0000ff'});
	$('#message-box form').remove();
	$('#message-box').hide();
	$('#shadow-box').hide();
	$('#button-fake').hide();
	$('#swfupload-control p object').show();
	return false;
}

function run_upload(url) {
	name_raw = url.split('/').pop();
	name = url.split('/').pop().toLowerCase().replace(/\./g, '_').replace(/\?/g, '_').replace(/\&/g, '_').replace(/\=/g, '_').replace(/\#/g, '_').replace(/\%/g, '_').replace(/\+/g, '_');
	var listitem='<tr id = "'+name+'" >'+
	'<td class = "file-name"><div>'+name_raw+'</div><div class = "hider"><img src = "' + baseUrl + '/img/common/file-name-tile.png" alt = "" title = "" /></div></td>'+
	'<td class = "status-thumbnail"><div style = "height: 30px; overflow: hidden; text-align: center;"><img src = "' + baseUrl + '/img/common/animated-progress.gif" alt = "" title = "" style = "margin-top: -85px;" /></div></td>'+
	'<td class = "describe">'+
	'</td>'+
	'</tr>';
	$('#log').append(listitem);
}
/*Add from url handlers starts*/
function add_from_url_handler() {
	var url = $('#upload-from-url .text input').val();
	name = url.split('/').pop().toLowerCase().replace(/\./g, '_').replace(/\?/g, '_').replace(/\&/g, '_').replace(/\=/g, '_').replace(/\#/g, '_').replace(/\%/g, '_').replace(/\+/g, '_');

	$.post(baseUrl + '/photo/chick-photo-upload-process', $('#upload-from-url').serialize(), function(data) {
		var data = $.parseJSON(data);
		$('#url-fake').val('');
		$('#'+name+' .status-thumbnail').html('<img src = "' + baseUrl + data.path + '" alt = "" title = "" width = "200" />');
		$('#log tr#'+name+' td.describe').html('<p><input type = "text" name = "form[UploadSave][doing]['+name+']" value = "What is she doing?" /></p><p><input type = "text" name = "form[UploadSave][look]['+name+']" value = "How does she look?" /></p><p><input type = "text" name = "form[UploadSave][wearing]['+name+']" value = "What is she wearing?" /><input type = "hidden" name = "form[UploadSave][file_name]['+name+']" value = "'+data.file_name+'" /></p>');
	});
	run_upload($('#upload-from-url .text input').val());
	$('#url-fake').val(url);
	$('#dialog').dialog("close");
}
$(document).ready(function() {
	$("#upload_from_url").click(function() {
		$('#swfupload-control p object').hide();
		$('#button-fake').show();
		var chick_id = $('#chick-id').val();
		var chick_name = $('#chick-name').val();
        $('#dialog').html('<form id = "upload-from-url" action = "#" method = "post"><p class = "input text"><label>Please paste URL in the field below</label><input type = "text" name = "form[UploadFromUrl][url]" /></p><input type = "hidden" name = "form[UploadFromUrl][chick_id]" value = "'+chick_id+'" /><input type = "hidden" name = "form[UploadFromUrl][chick_name]" value = "'+chick_name+'" /></form>');
        $('#dialog').dialog({
            title: 'Add from url',
            width: 300,
            height: 170,
            buttons: {
                "Upload": function() {
                    add_from_url_handler();
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            },
            beforeClose: function(){
            		$('#swfupload-control p object').show();
            		$('#button-fake').hide();
            	}
        });
        $('#dialog').dialog('open');
		return false;
	});
	
    $("#close-button").click(function () {return hide_popup();});

});
/*Add from url handlers ends*/

/*Add video starts*/
$(document).ready(function() {
	$("#add-button").bind('click', function() {
		var url = $('#url').val();
		if(url != ''){
			var chick_id = $('#chick_id').val();
			name = url.split('/').pop().toLowerCase().replace(/\./g, '_').replace(/\?/g, '_').replace(/\&/g, '_').replace(/\=/g, '_').replace(/\#/g, '_');
			start_video_upload(url);
			$.post(baseUrl + '/video/chick-video-upload-process', { url: url, chick_id: chick_id}, function(data) {
				var data = $.parseJSON(data);
				$('#' + name + ' .status-thumbnail').html('<img src = "' + data.thumbnail + '" alt = "" title = "" width = "200" />');
				$('#log tr#' + name + ' td.describe').html('<p><input type = "text" name = "form[UploadSave][title][' + name + ']" value = "' + data.title + '" /></p>' + 
	            '<p><textarea name = "form[UploadSave][description][' + name + ']" cols = "30" rows = "5">' + data.description + '</textarea><input type = "hidden" name = "form[UploadSave][url][' + name + ']" value = "' + data.url + '" /></p>');
	            $('#url').val('');
			});
		}else{
			alert('Please enter the URL of a video!');
		}
		return false;
	});

});
function start_video_upload(url) {
	name = url.split('/').pop().toLowerCase().replace(/\./g, '_').replace(/\?/g, '_').replace(/\&/g, '_').replace(/\=/g, '_').replace(/\#/g, '_');
	var listitem='<tr id = "'+name+'" >'+
	'<td class = "file-name"><div>'+url+'</div><div class = "hider"><img src = "' + baseUrl + '/img/common/file-name-tile.png" alt = "" title = "" /></div></td>'+
	'<td class = "status-thumbnail"><div style = "height: 30px; overflow: hidden; text-align: center;"><img src = "' + baseUrl + '/img/common/animated-progress.gif" alt = "" title = "" style = "margin-top: -85px;" /></div></td>'+
	'<td class = "describe">'+
	'</td>'+
	'</tr>';
	$('#log').append(listitem);
}
/*Add video ends*/


/*Sorting on photo and video pages starts*/
$(document).ready(function() {
    $("#sort-order").bind('change', function() {
        $(this).parent().submit();
    });
});
/*Sorting on photo and video pages ends*/

/*Peporting on photo and video page starts*/
$(document).ready(function() {
    $("#report-link-photo").click(function() {
        var src = $('#chick_photo_carousel li img').attr('src').replace('585x795', '150x150');
        var slug = $('#chick_photo_carousel li img').attr('slug');
        var title = $('#chick_photo_carousel li img').attr('title');
        $('#dialog').html('<form id = "ReportForm" action = "#" method = "post" name = "form[Report]">' + 
            '<div class = "input image"><label>Photo:</label><p style = "width: 100px; display: inline-block; vertical-align: middle;"><img src = "' + src + '" alt = "' + title + '" title = "' + title + '"></p></div>' + 
            '<div class = "input textarea"><label>Comment:</label><textarea name = "form[Report][comment]" cols = "30" rows = "5"></textarea><input type = "hidden" name = "form[Report][slug]" value = "' + slug + '" /></div>' + 
            '</form>');
        $('#dialog').dialog({
            title: 'Report photo',
            height: 350,
            width: 300,
            buttons: {
                "Report": function() {
                    ReportPhoto();
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        });
        $('#dialog').dialog('open');
        return false;
    });
});
function ReportPhoto() {
    if ($('#ReportForm .textarea textarea').val() == '') {
        alert('Sorry but `comment` is required field');
        return false;
    }
    var data_to_send = $('#ReportForm').serialize();
    $('#message-box form').remove();
    $('#message-box').append('<img src = "' + baseUrl + '/img/common/spinner.gif" alt = "Loading, please wait" title = "Loading, please wait" />');
    $.post(baseUrl + '/photo/media-report', data_to_send, function(data) {
        $('#dialog').dialog("close");
    });
    return false;
}

$(document).ready(function() {
    $("#report-link-video").bind('click', function() {
        var slug = $('#report-link-video').attr('href').split('/').pop();
        //var title = $('#chick-video-title').text();
        var title='';
        //title=title.replace('/(["\'\])/g', "\\$1").replace('/\0/g', "\\0");
        var thumbnail = $('#thumbnail-url').val();
        /*$('#player-container object').append('<param name = "wmode" value = "transparent"></param>');
        $('#player-container object embed').attr("wmode", "transparent");*/
        $('#shadow-box').css({opacity: 0.5}).fadeIn('slow', function() {
            $('#message-box').append('<form id = "ReportForm" action = "" onsubmit = "return ReportVideo();" method = "post" name = "form[Report]">' + 
            '<div class = "input text"><label>Thumbnail:</label><p style = "width: 220px; display: inline-block;"><img src = "'+ thumbnail + '" alt = "' + title + '" title = "' + title + '" style = "max-width: 220px;_width: 220px;"></p></div>' + 
            '<div class = "input textarea"><label>Comment:</label><textarea name = "form[Report][comment]" cols = "30" rows = "5"></textarea></div>' + 
            '<div class = "input submit"><input type = "hidden" name = "form[Report][slug]" value = "' + slug + '" /><input type = "submit" name = "form[Report][submit]" value = "Report" /></textarea></div>' + 
            '</form>');
            var left_pos = $('body').outerWidth()/2 - $('#message-box').outerWidth()/2;
            var top_pos = $('body').outerHeight()/2 - $('#message-box').outerHeight()/2;
            $('#message-box').css({opacity: 1, left: left_pos, top: top_pos}).show();
        });
        return false;
    });
});
function ReportVideo() {
    if ($('#ReportForm .textarea textarea').val() == '') {
        alert('Sorry but `comment` is a required field');
        return false;
    }
    
    var data_to_send = $('#ReportForm').serialize();
    $('#message-box form').remove();
    $('#message-box').append('<img src = "' + baseUrl + '/img/common/spinner.gif" alt = "Loading, please wait" title = "Loading, please wait" />');
    $.post(baseUrl + '/video/media-report', data_to_send, function(data) {
        $('#message-box img').remove();
        hide_popup();
    });
    return false;
}
/*Peporting on photo and video page ends*/

/*Popup hidden-tip on chick page starts*/
$(document).ready(function() {
    $('#chick_article #avatar').mouseover(function(e) {
        var posX = e.pageX;
        var posY = e.pageY;
        timer = setTimeout('show_tip(' + posX + ', ' + posY + ')', 2000);
    });
    $('#chick_article #avatar').mouseout(function() {
        clearTimeout(timer);
        $('#chick_article .hidden-tip').hide();
    });
});
function show_tip(posX, posY) {
    //alert(posX +', '+ posY);
    var avatar_pos = $('#chick_article #avatar').offset();
    $('#chick_article .hidden-tip').css({display: 'block', top: posY - 400, left: posX - 200});
}

function htmlspecialchars_decode (string, quote_style) {
    // Convert special HTML entities back to characters  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/htmlspecialchars_decode    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');    // *     returns 1: '<p>this -> &quot;</p>'
    // *     example 2: htmlspecialchars_decode("&amp;quot;");
    // *     returns 2: '&quot;'
    var optTemp = 0, i = 0, noquotes = false;
    if (typeof quote_style === 'undefined') {        
        quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,        
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4    
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;            
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }        
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP    
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded    string = string.replace(/&amp;/g, '&');
 
    return string;
}
/*Popup hidden-tip on chick page ends*/

/* search twitter */
function search_twitter(search,id,count){
	String.prototype.parseURL = function() {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
			return url.link(url);
		});
	};
	String.prototype.parseUsername = function() {
		return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
			var username = u.replace("@","")
			return u.link("http://twitter.com/"+username);
		});
	};
	String.prototype.parseHashtag = function() {
		return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
			var tag = t.replace("#","%23")
			return t.link("http://search.twitter.com/search?q="+tag);
		});
	};
	
	$.ajax({  
	    url : "http://search.twitter.com/search.json?q="+search+"&callback=?",  
	    dataType : "json",  
	    timeout:15000,  
	
	    success : function(data)  
	    { 
	    	
				text='';
				for (var key in data.results) {
	    			if (key==count) break;
					var val = data.results [key];
					time=val.created_at;
					text=text+'<tr><td width="55"><img width="48" class="avatar_comment" src = "'+val.profile_image_url+'" /></td><td><div class="top_name_comment"><a href="http://twitter.com/'+val.from_user+'" rel="nofollow">'+val.from_user+'</a></div><div class="text_comment">'+val.text.parseURL().parseUsername().parseHashtag()+'</div><div class="time_comment">'+sumTime(val.created_at)+'</div></td></tr>';
				} 
				$('#'+id).html(text);
	    },  
	
	    error : function()  
	    {    }  
	
	});
}
function sumTime(time){
var d = new Date();
var time= new Date(time);
time_delta=d-time;
var sec=Math.floor(time_delta/1000);
var min=Math.floor(sec/60);
var hours=Math.floor(min/60);
var day=Math.floor(hours/24);
sec=sec-min*60;
min=min-hours*60;
hours=hours-day*24;
var date_delta='';
if (day>0)
	date_delta=date_delta+day+' day ';
if (hours>0)
	date_delta=date_delta+hours+' hours ';
if (min>0)
	date_delta=date_delta+min+' min ';
if (date_delta=='')
	date_delta=date_delta+sec+' sec ';
date_delta=date_delta+'ago';
return date_delta;
}
/* search twitter */

/* popaps */
$(document).ready(function() {
	var chick_name = $('#chick_name').text();
    $("#rename_chick").bind('click', function() {
        $('#shadow-box').css({opacity: 0.5}).fadeIn('slow', function() {
            $('#message-box').append('<form id = "RenameForm" action = "/1" onsubmit = "return sendForm(\'RenameForm\', true);" method = "post" name = "form[Rename]">' + 
            '<div style="text-align:left;"><strong>New Name</strong></div>' + 
            '<div><input type = "text" value = "' + chick_name.replace('"', '&quot;').replace('\'', '&#039;') + '" name="form[Rename][name]" /></div>' + 
            '<div style="text-align:right;"><input type = "submit" name = "form[Rename][submit]" value = "Save" /></div>' + 
            '</form>');
            var el=document.getElementById("rename_chick");
            var pos=getOffset(el);
            var left_pos = pos.left+30;
            var top_pos = pos.top+20;
            $('#message-box').css({opacity: 1, left: left_pos, top: top_pos}).show();
        });
        return false;
    });
    $("#delete_dude").bind('click', function() {
        $('#shadow-box').css({opacity: 0.5}).fadeIn('slow', function() {
            $('#message-box').append('<form id = "DeleteForm" action = "" onsubmit = "return sendForm(\'DeleteForm\');" method = "post" name = "form[Delete]">' + 
            '<div style="text-align:left;"><strong>Are you sure you want to delete this article?</strong></div>' + 
            '<div style="text-align:center;"><input type = "submit" name = "form[Delete][submit]" value = "Delete" /></div>' + 
            '</form>');
            el=document.getElementById("delete_dude");
            var pos=getOffset(el);
            var left_pos = pos.left+30;
            var top_pos = pos.top+20;
            $('#message-box').css({opacity: 1, left: left_pos, top: top_pos}).show();
        });
        return false;
    });
    $("#delete_chick").bind('click', function() {
        $('#shadow-box').css({opacity: 0.5}).fadeIn('slow', function() {
            $('#message-box').append('<form id = "DeleteForm" action = "" onsubmit = "return sendForm(\'DeleteForm\');" method = "post" name = "form[Delete]">' + 
            '<div style="text-align:left;"><strong>Are you sure you want to delete this article?</strong></div>' + 
            '<div style="text-align:center;"><input type = "submit" name = "form[Delete][submit]" value = "Delete" /></div>' + 
            '</form>');
            el=document.getElementById("delete_chick");
            var pos=getOffset(el);
            var left_pos = pos.left+30;
            var top_pos = pos.top+20;
            $('#message-box').css({opacity: 1, left: left_pos, top: top_pos}).show();
        });
        return false;
    });
    $("#protection_chick").bind('click', function() {
        $('#shadow-box').css({opacity: 0.5}).fadeIn('slow', function() {
            if ($("#protection_chick").attr('role') == 0)
                var selected_none = 'checked = "checked"';
            else
                var selected_none = '';
            if ($("#protection_chick").attr('role') == 50)
                var selected_contributor = 'checked = "checked"';
            else
                var selected_contributor = '';
            if ($("#protection_chick").attr('role') == 100)
                var selected_editor = 'checked = "checked"';
            else
                var selected_editor = '';
            if ($("#protection_chick").attr('role') == 200)
                var selected_admin = 'checked = "checked"';
            else
                var selected_admin = '';
            $('#message-box').append('<form id = "ProtectionForm" action = "" onsubmit = "return sendForm(\'ProtectionForm\');" method = "post" name = "form[Protection]">' + 
            '<div style="text-align:left;">Edit minimum priveleges to edit <strong>'+chick_name+'</strong></div>' + 
            '<input type = "radio" name="form[Protection][priveleges]" value="0" ' + selected_none + ' /> None <br />' + 
            '<input type = "radio" name="form[Protection][priveleges]" value="50" ' + selected_contributor + ' /> Contributor <br />' +
            '<input type = "radio" name="form[Protection][priveleges]" value="100" ' + selected_editor + ' /> Editor <br />' +
            '<input type = "radio" name="form[Protection][priveleges]" value="200" ' + selected_admin + ' /> Admin <br />' +
            '<div style="text-align:center;"><input type = "submit" name = "form[Protection][submit]" value = "Save" /></div>' + 
            '</form>');
            el=document.getElementById("protection_chick");
            var pos=getOffset(el);
            var left_pos = pos.left+30;
            var top_pos = pos.top+20;
            $('#message-box').css({opacity: 1, left: left_pos, top: top_pos}).show();
        });
        return false;
    });
    $("#redirects_chick").bind('click', function() {
        $('#shadow-box').css({opacity: 0.5}).fadeIn('slow', function() {
            var text = $('#alias').html();
            if (text == null) text = '';
        	var text2 = $('#alias_id').html();
        	if (text2 == null) text2 = '';
            $('#message-box').append('<form id = "RedirectsForm" action = "" onsubmit = "return sendForm(\'RedirectsForm\',1);" method = "post" name = "form[Redirects]">' + 
            '<div style="text-align:left;"><strong>Terms that redirect here:</strong></div>' + 
            '<div id = "alias2">'+
            text +
            '</div>'+
            text2 +
            '<div style="text-align:center;"><input type = "text" name = "form[Redirects][alias]" /></div>'+
            '<div style="text-align:center;"><input type = "submit" name = "form[Redirects][submit]" value = "Save" /></div>' + 
            '</form>');
            el=document.getElementById("redirects_chick");
            var pos=getOffset(el);
            var left_pos = pos.left+30;
            var top_pos = pos.top+20;
            $('#message-box').css({opacity: 1, left: left_pos, top: top_pos}).show();
        });
        return false;
    });
});

function sendForm(form,ajax){
	var slug_url=$('#slug').val();
	var url='';
	switch (form){
		case 'RenameForm': url=slug_url+'/rename/';break;
		case 'DeleteForm': url=slug_url+'/delete/';break;
		case 'ProtectionForm': url=slug_url+'/protection/';break;
		case 'EditRelations': url=$('#' + form).attr('action');break;
		case 'RedirectsForm': url=slug_url+'/aliases/';break;
	}
	if (typeof ajax != "undefined"){
		var dat=$('#' + form).serialize();
        if (form == 'RenameForm')
		    $.post(url,dat, function(data) {
                if (data == 'exist')
                    alert('Another article with that name exists!');
                else if (data == 'not-informative')
                    alert('Title for this chick is not informative!');
                else{
                	var dat = $.parseJSON(data);
                	if (dat.message=='good'){
                		window.location = baseUrl + '/' + dat.slug;
                	}else if(dat.message=='permissions'){
                        hide_popup ();
                        alert(dat.text);
                        window.location = slug_url;
                	}
                }
            });
        else{
        	if (form == 'RedirectsForm'){
        		$.post(url,dat,function(data) {
        			if (data!='')
        			if (data == 'error'){
        				alert("Please enter a valid alias!");
        			}else{
        				if (data == 'error1'){
        					alert("The alias cannot be the same as the main chick URL!");
        				}else{
        					if (data == 'error2' || data == 'error3'){
        						alert("This alias is already in use!");
        					}else{
                                if ($('#alias').length == 0)
                                    $('#alias_id').before('<div id = "alias" style = "display: none;">' + data + '</div>');
                                else
        						    $('#alias').html(data);
                                    
                                $('#alias2').html(data);
        			        	$('#RedirectsForm input:[name="form[Redirects][alias]"]').val('');
        					}
        				}
        			}
        		});
        	}else if (form == 'EditRelations'){
                $('#' + form).submit();
                $.post(url,dat, function() {
                    window.location = baseUrl + '/' + $('#' + form).attr('slug') + '/';
                })
            } else {
        		$.post(url,dat);
        	}
        }
		return false;
	}else{
		var formsub=document.getElementById(form);
		$(formsub).attr('action', url);
		return true;
	}
}

function getOffset(elem) {
    if (elem.getBoundingClientRect) {
        return getOffsetRect(elem);
    } else {
        return getOffsetSum(elem);
    }
}
function getOffsetRect(elem) {

    var box = elem.getBoundingClientRect();
    
    var body = document.body;
    var docElem = document.documentElement;
    
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
    
    var clientTop = docElem.clientTop || body.clientTop || 0;
    var clientLeft = docElem.clientLeft || body.clientLeft || 0;
    
    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;
    
    return { top: Math.round(top), left: Math.round(left) }
}
function getOffsetSum(elem) {
    var top=0, left=0;
    while(elem) {
        top = top + parseInt(elem.offsetTop);
        left = left + parseInt(elem.offsetLeft);
        elem = elem.offsetParent;       
    }
    return {top: top, left: left}
}

/* popaps */


/*Chick add popup starts (from drop down menu)*/
$(document).ready(function() {
    $('#dialog').click(function() {
        $('#dialog .suggester').remove();
    });
    $('#add-chick-dropdown').click(function() {
        $('#dialog').html('<form id = "PageAdd" action = "' + baseUrl + '/index/page-add" method = "post" name = "form[PageAdd]">' + 
            '<div class = "input text"><label for = "PageName">Enter Сhick Name:</label><input type = "text" onkeydown = "return ignoreEnterOnDialog(event)" onkeyup = "return AutoSuggestPageName(this, event)" id = "PageName" name = "form[PageAdd][name]" value = "" /></div>' + 
        '</form>');
        $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, height: 250, width: 320, title: 'Add chick',
            buttons: {
                "Save": function() {
                    pageAdd('chick');
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        });
        $('#dialog').dialog('open');
        setTimeout("$('#PageName').focus()", 500);
        
        
        return false;
    });
});



/*Chick add popup starts*/
$(document).ready(function() {
    $('#dialog').click(function() {
        $('#dialog .suggester').remove();
    });
    $('#add-chick').click(function() {
        $('#dialog').html('<form id = "PageAdd" action = "' + baseUrl + '/index/page-add" method = "post" name = "form[PageAdd]">' + 
            '<div class = "input text"><label for = "PageName">Enter Сhick Name:</label><input type = "text" onkeydown = "return ignoreEnterOnDialog(event)" onkeyup = "return AutoSuggestPageName(this, event)" id = "PageName" name = "form[PageAdd][name]" value = "" /></div>' + 
        '</form>');
        $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, height: 250, width: 320, title: 'Add chick',
            buttons: {
                "Save": function() {
                    pageAdd('chick');
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        });
        $('#dialog').dialog('open');
        setTimeout("$('#PageName').focus()", 500);
        
        
        return false;
    });
});

function ignoreEnterOnDialog(event) {
    if (event.keyCode==13) {
        return false;
    }
}

function AutoSuggestPageName(element, event) {
    $('#PageAdd .suggester').remove();
    if (event.keyCode == 27 || event.keyCode == 16 || event.keyCode == 17 || event.keyCode == 18 || event.keyCode == 13) {
        return false;
    }
    $.post(baseUrl + '/photo/chick-autocomplite', {'value': $(element).val(), 'id':element.id, 'event':'pageAdd'}, function(data) {
        var data = $.parseJSON(data);
        if (data == null)
            return;
        var values = '';
        var row = '';
        var count = 0;
        for (k in data) {
            if (data.hasOwnProperty(k)) {
                if (count % 2 == 0)
                    row = 'even';
                else
                    row = 'odd';
                values = values + '<p onclick = "window.location = \'' + baseUrl + '/' + data[k].chick_slug + '/\'" class = "' + row + '" id = "chick-' + k + '">' + data[k].chick_name + '</p>';
                count++;
            }
        }
        $(element).after('<div class = "suggester">' + values + '</div>');
    });
}

function pageAdd(type, search) {

    if ($('#PageName').val() == '') {
        return false;
    }
    
    $.post(baseUrl + '/index/page-add-check', {'page_title': $('#PageName').val()}, function(data) {
        
    var data = $.parseJSON(data);

    switch(data['action']) {
            case 'exist':
                $('#dialog').html('<p class = "pageAddMessage">Sorry, but page for this ' + type + ' already exists!<br />You can visit it by clicking the following link: <a href = "' + baseUrl + '/' + data['slug'] + '/">' + data['title'] + '</a></p>');
                $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, title: 'Add page',
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $('#dialog').dialog('open');
            break;
            case 'deleted':
                $('#dialog').html('<p class = "pageAddMessage">This page is under review</p>');
                $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, title: 'Add page',
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $('#dialog').dialog('open');
            break;
            case 'banned':
                $('#dialog').html('<p class = "pageAddMessage">The title contains a banned word: "' + data['term'] + '".</p>');
                $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, title: 'Add page',
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $('#dialog').dialog('open');
            break;
            case 'throttle':
                $('#dialog').html('<p class = "pageAddMessage">Sorry, chickipedia is under heavy load at the moment and we can\'t process your request right now. Please try again in an hour!</p>');
                $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, title: 'Add page',
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $('#dialog').dialog('open');
            break;
            case 'not_logged':
                $('#dialog').html('<p class = "pageAddMessage">To save the chick you should be logged in!</p><br /><br /><a href="#" onclick = "toggleUserLinks(\'login_box\'); $(\'#dialog\').dialog(\'close\'); return false;">Clik here to Login</a> or <a href="/chickipedia/createaccount">Create an Account</a>');
                $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, title: 'Add page',
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $('#dialog').dialog('open');
            break;
            case 'permissions':
                $('#dialog').html('<p class = "pageAddMessage">You don\'t have permissions to add this page!</p>');
                $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, title: 'Add page',
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $('#dialog').dialog('open');
            break;
            case 'not-informative':
            	$('#dialog').html('<p class = "pageAddMessage">Title for this chick is not informative!</p>');
                $('#dialog').dialog({show: "drop", hide: "drop", modal: true, resizable: false, title: 'Add page',
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $('#dialog').dialog('open');
            break;
            case 'success':
                if (search == true) {
                   $('#SearchPageAdd').submit();
                } else {
                    $('#PageAdd').submit();
                }
            break;
        }
    });    
    return false;
}
/*Chick add popup ends*/

function updateDay(yearName,monthName,dayName,func){
	var year=document.getElementById(yearName).value;
	var month=document.getElementById(monthName).value;
	var day=document.getElementById(dayName).value;
	
	var day_max=0;
	
	day_max=(month!=2?((month%2)^(month>7))+30:(!(year%400)||!(year%4)&&(year%25)?29:28));
	
	if (day_max<day){
		day=day_max;
	}
	var op='';
	for (i=1;i<=day_max;i++){
		if (i==day){
			if (i<10){
				i='0'+i;
			}
			op=op+'<option value="'+i+'" selected>'+i+'</option>';
		}else{
			if (i<10){
				i='0'+i;
			}
			op=op+'<option value="'+i+'">'+i+'</option>';
		}
	}
	document.getElementById(dayName).innerHTML='';
	document.getElementById(dayName).innerHTML=op;
	$('#'+dayName).html(op);
	if (func)
		func();
}
function get_zodiac(){
	var month=document.getElementById('month').value;
	var day=document.getElementById('day').value;
	   if (month == 1 && day <=20) {value = "Capricorn";}
	   if (month == 1 && day >=21) {value = "Aquarius";}
	   if (month == 2 && day <=20) {value = "Aquarius";}
	   if (month == 2 && day >=21) {value = "Pisces";}
	   if (month == 3 && day <=20) {value = "Pisces";}
	   if (month == 3 && day >=21) {value = "Aries";}
	   if (month == 4 && day <=20) {value = "Aries";}
	   if (month == 4 && day >=21) {value = "Taurus";}
	   if (month == 5 && day <=20) {value = "Taurus";}
	   if (month == 5 && day >=21) {value = "Gemini";}
	   if (month == 6 && day <=21) {value = "Gemini";}
	   if (month == 6 && day >=22) {value = "Cancer";}
	   if (month == 7 && day <=22) {value = "Cancer";}
	   if (month == 7 && day >=23) {value = "Leo";}
	   if (month == 8 && day <=23) {value = "Leo";}
	   if (month == 8 && day >=24) {value = "Virgo";}
	   if (month == 9 && day <=23) {value = "Virgo";}
	   if (month == 9 && day >=24) {value = "Libra";}
	   if (month == 10 && day <=23) {value = "Libra";}
	   if (month == 10 && day >=24) {value = "Scorpio";}
	   if (month == 11 && day <=22) {value = "Scorpio";}
	   if (month == 11 && day >=23) {value = "Sagittarius";}
	   if (month == 12 && day <=21) {value = "Sagittarius";}
	   if (month == 12 && day >=22) {value = "Capricorn";}

	   $('#sign :contains('+value+')').attr("selected", "selected");
	   
//	   document.getElementById('sign').value=value;
}
function wikiWindow(url,slug,editior){
	htmlstart='<html><head><title>chickipedia</title><link type="text/css" rel="stylesheet" media="screen" href="'+url+'/styles/default.css"></head><body><div id="middle" style="width:685px;"><div class="middle-line"><div id="content" style="float:none;"><div class="content-block block page_article content-wrapper-block" id="chick_article"><div class="block-content-wrapper"><div class="article" style="background:#F7F7F7;">';
	htmlend='<div class="clear"></div></div></div></div></div></div></div></body></html>';
	//render();
	$.post(baseUrl + '/index/wiki-Window', {slug: slug, body: $('#'+editior).val()}, function(data) {
		var win=window.open('','new','width=800,height=600,toolbar=0,scrollbars=1');
		win.document.open();
		win.document.write(htmlstart+''+data+''+htmlend);
		win.document.close();
		win.focus();
	});
}

/*Rating starts*/
function rateIt(type, value) {
    var id = $('#rating').attr(type + '_id');
    var rating = parseInt($('.rate #rating:first').text());
    if (value == '1') {
        $('.rate').html('<span id = "rating" ' + type + '_id = "' + id + '">' + (rating + 1) + '</span><span><img src = "' + baseUrl + '/img/common/thumb_up_dis.png" alt = "Thumb it up" title = "Thumb it up" /></span><span id = "thumb_down" onclick = "return rateIt(\'' + type + '\', \'-1\');"><img src = "' + baseUrl + '/img/common/thumb_down.png" alt = "Thumb it down" title = "Thumb it down" /></span>');
    }
    else {
        $('.rate').html('<span id = "rating" ' + type + '_id = "' + id + '">' + (rating - 1) + '</span><span id = "thumb_up" onclick = "return rateIt(\'' + type + '\', \'1\');"><img src = "' + baseUrl + '/img/common/thumb_up.png" alt = "Thumb it up" title = "Thumb it up" /></span><span><img src = "' + baseUrl + '/img/common/thumb_down_dis.png" alt = "Thumb it down" title = "Thumb it down" /></span>');
    }
    $.post(baseUrl + '/index/vote', {type: type, value: value, id: id}, function(data) {});
    return false;
}
/*Rating ends*/

/*Relations autosuggester starts*/
function AutoSuggestRelations(element, event) {
    $('#EditRelations .suggester').remove();
    if (event.keyCode == 27 || event.keyCode == 16 || event.keyCode == 17 || event.keyCode == 18) {
        return;
    }
    $(element).blur(function() {
        setTimeout(function(){$('#EditRelations .suggester').remove();},200);
    });
    var element_values = $(element).val().split(',');
    $.post(baseUrl + '/photo/chick-autocomplite', {'value': element_values.pop(), 'type':$(element).attr('page_type'), 'id':element.id, 'event':'editRelations'}, function(data) {
        var data = $.parseJSON(data);
        if (data == null)
            return;
        var values = '';
        var row = '';
        var count = 0;
        for (k in data) {
            if (data.hasOwnProperty(k)) {
                if (count % 2 == 0)
                    row = 'even';
                else
                    row = 'odd';
                
                if ($(element).val() == '' || $(element).val() == ',') {
                    var data_to_insert = data[k].chick_name;
                } else {
                    var element_values = $(element).val().split(',');
                    last_item = element_values.pop();
                    element_values.push(data[k].chick_name);
                    var data_to_insert = element_values.join(', ');
                }
                data_to_insert=data_to_insert.replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
                values = values + '<p onclick = "$(\'#' + element.id + '\').val(\''+data_to_insert+'\')" class = "' + row + '" id = "chick-' + k + '">' + data[k].chick_name + '</p>';
                count++;
            }
        }
        $('#' + element.id).after('<div class = "suggester">' + values + '</div>');
    });
}
/*Relations autosuggester ends*/

/*Revisions rolback starts*/
$(document).ready(function() {
    $('#rollback_button').click(function() {
        if (!confirm('Are you sure you want to roll back this revision?')) {
            return false;
        } 
        $.post(baseUrl + '/index/rollback-revision', {'page_slug': $('#rollback_button').attr('page_slug'), 'revision_id': $('#rollback_button').attr('revision_id')}, function(data) {
            window.location = baseUrl + '/' + $('#rollback_button').attr('page_slug') + '/history/';
        });
        return false;
    });
    $('#rollback_undo_button').click(function() {
        if (!confirm('Are you sure you want to roll back this revision?')) {
            return false;
        } 
        $.post(baseUrl + '/index/rollback-revision', {'page_slug': $('#rollback_undo_button').attr('page_slug'), 'revision_id': $('#rollback_undo_button').attr('revision_id'),'undo':'undo'}, function(data) {
            window.location = baseUrl + '/' + $('#rollback_undo_button').attr('page_slug') + '/history/';
        });
        return false;
    });
});
/*Revisions rolback ends*/

/*Tags administration scripts starts*/
$(document).ready(function() {
    $('#change-state').click(function () {
        var boxes = new Array();
        $('table input:checkbox').each(function() {
            if ($(this).parent().parent().css('display') !== 'none') {
                boxes[boxes.length] = $(this).attr('name') + ':' + ((this.checked)?1:0);
            }
        });
        $.post(baseUrl + '/tags/exclude/', {'boxes':boxes}, function(data) {alert('Exclusion saved!')});
        return false;
    });
    $('#tag_administration table tr td input:checkbox').live('click', function() {
        var tag_id = $(this).parent().parent().attr('id');
        if (tag_id.indexOf('edit_') == '-1') {
            if (this.checked == false)
                $('#edit_' + tag_id + ' td input:checkbox').removeAttr('checked');
            else
                $('#edit_' + tag_id + ' td input:checkbox').attr('checked', 'checked');
        }
        else {
            if (this.checked == false)
                $('#' + tag_id.replace('edit_', '') + ' td input:checkbox').removeAttr('checked');
            else
                $('#' + tag_id.replace('edit_', '') + ' td input:checkbox').attr('checked', 'checked');
        }
    });
    $('#tag_administration table tr td .delete-link').live('click', function() {
        var tag_id = $(this).parent().parent().attr('id');
        if (!confirm('Are you sure you want to delete "' + $('#' + tag_id + ' td.name').text() + '" tag?')) {
            return false;
        }
        $.post(baseUrl + '/tags/delete', {'id':parseInt(tag_id.replace('tag_row_', ''))}, function(data) {
            $('#' + tag_id).remove();
            $('#edit_' + tag_id).remove();
            alert('Tag succesfully deleted!');
        });
        return false;
    });
    $('#tag_administration table tr td .edit-link').live('click', function() {
        var tag_id = $(this).parent().parent().attr('id');
        $('#' + tag_id).hide();
        $('#edit_' + tag_id).show();
        $('#edit_'+tag_id+' .name input').val($('#'+tag_id+' .name').text());
        $('#edit_'+tag_id+' .display-name input').val($('#'+tag_id+' .display-name').text());
        return false;
    });
    $('#tag_administration table tr td .cancel-link').live('click', function() {
        var tag_id = $(this).parent().parent().attr('id');
        $('#' + tag_id).hide();
        $('#' + tag_id.replace('edit_', '')).show();
        return false;
    });
    $('#add-tag').live('click', function () {
        if ($('#tag_administration table tr:last').attr('id').indexOf('new_tag_row_') == '-1')
            var added_row = 'new_tag_row_1';
        else {
            var index = parseInt($('#tag_administration table tr:last').attr('id').replace('new_tag_row_', '')) + 1;
            var added_row = 'new_tag_row_' + index;
        }
        if ($('#tag_administration table tr:last').hasClass('odd') == true)
            var row_class = 'even';
        else
            var row_class = 'odd';
        //array('-','Assets','Birthday','Country','Ethnicity','Eyes','Hair','Hobbies','Hometown','Job','Piercings','Tattoos','Vices');
        $('#tag_administration table').append('<tr class = "new ' + row_class + '" id = "' + added_row + '">' + 
        '<td class = "name"><input type = "text" name = "form[EditTag][name]" value = "" /></td>' + 
        '<td class = "slug"></td>' + 
        '<td class = "display-name"><input type = "text" name = "form[EditTag][display-name]" value = "" /></td>' + 
        '<td class = "members"></td>' + 
        '<td class = "group"><select name = "form[EditTag][group]"><option value = "-" >-</option><option value = "Assets" >Assets</option><option value = "Birthday" >Birthday</option><option value = "Country" >Country</option><option value = "Ethnicity" >Ethnicity</option><option value = "Eyes" >Eyes</option><option value = "Hair" >Hair</option><option value = "Hobbies" >Hobbies</option><option value = "Hometown" >Hometown</option><option value = "Job">Job</option><option value = "Piercings" >Piercings</option><option value = "Tattoos" >Tattoos</option><option value = "Vices" >Vices</option></select></td>' + 
        '<td><input type = "checkbox" name = "" /></td>' + 
        '<td class = "operations"><a href = "#" class = "save-link" onclick = "return save_tag_row(\'add\', \'' + added_row + '\');">Save</a> | <a href = "#" class = "cancel-link" onclick = "return cancel_tag_row(\'add\', \'' + added_row + '\');">Cancel</a></td>' + 
        '</tr>');
        var position = $('#' + added_row).offset();
        window.scrollTo(0, position.top);
        return false;
    });
});
function cancel_tag_row(type, id) {
    if (type == 'add') {
        $('#' + id).remove();
        return false;
    }
}
function save_tag_row(type, id) {
    if (type == 'edit')
        var tag_id = parseInt(id.replace('edit_tag_row_', ''));
    else
        var tag_id = '';
    var name = $('#' + id + ' td.name input').val();
    var display_name = $('#' + id + ' td.display-name input').val();
    var group = $('#' + id + ' td.group select').val();
    var exclude = $('#' + id + ' td input:checked').attr('checked');
    $.post(baseUrl + '/tags/save', {'id':tag_id, 'name':name, 'display_name':display_name, 'group':group, 'exclude':(exclude)?'1':'0'}, function(data) {
        if (data == 'false') {
            alert('Sorry, but tag with this name already exist!');
            return false;
        }
        if (data == 'banned') {
            alert('The name of tag contains a banned word!');
            return false;
        }
        var data = $.parseJSON(data);
        if (type == 'edit') {
            $('#' + id.replace('edit_', '') + ' td.name').text(name);
            $('#' + id.replace('edit_', '') + ' td.display-name').text(display_name);
            $('#' + id.replace('edit_', '') + ' td.group').text(group);
            $('#' + id.replace('edit_', '') + ' td.slug').text(data['slug']);
            if (data['group']=='-')
            	$('#' + id.replace('edit_', '') + ' td.members').text('-');
            else
            	$('#' + id.replace('edit_', '') + ' td.members').html('<a href = "'+baseUrl+'/tags/'+data['group']+'/'+data['slug']+'">'+data['members']+'</a>');
            $('#' + id + ' td.slug').text(data['slug']);
            $('#' + id).hide();
            $('#' + id.replace('edit_', '')).show();
        }
        if (type == 'add') {
            //should to be replaced with data.id
            $('#' + id).remove();
            if ($('#tag_administration table tr#id').hasClass('odd') == true)
                var row_class = 'odd';
            else
                var row_class = 'even';
            
            if (data['group']=='-')
            	var link='-';
            else
            	var link='<a>0</a>';
            
            $('#tag_administration table').append('<tr class = "' + row_class + '" id = "tag_row_' + data.tag_id + '">' + 
            '<td class = "name">' + data.name + '</td>' + 
            '<td class = "slug">' + data.slug + '</td>' + 
            '<td class = "display-name">' + data.display_name + '</td>' + 
            '<td class = "members">'+link+'</td>' + 
            '<td class = "group">' + group + '</td>' + 
            '<td><input type = "checkbox" name = "" /></td>' + 
            '<td class = "operations"><a href = "#" class = "delete-link">Delete</a> | <a href = "#" class = "edit-link">Edit</a></td>' + 
            '</tr>');
            $('#tag_administration table').append('<tr class = "hidden ' + row_class + '" id = "edit_tag_row_' + data.tag_id + '">' + 
            '<td class = "name"><input type = "text" name = "form[EditTag][name]" value = "' + data.name + '" /></td>' + 
            '<td class = "slug">' + data.slug + '</td>' + 
            '<td class = "display-name"><input type = "text" name = "form[EditTag][display-name]" value = "' + data.display_name + '" /></td>' + 
            '<td class = "members">'+link+'</td>' + 
            //data.group
            '<td class = "group"><select name = "form[EditTag][group]"><option value = "-" >-</option><option value = "Assets" >Assets</option><option value = "Birthday" >Birthday</option><option value = "Country" >Country</option><option value = "Ethnicity" >Ethnicity</option><option value = "Eyes" >Eyes</option><option value = "Hair" >Hair</option><option value = "Hobbies" >Hobbies</option><option value = "Hometown" >Hometown</option><option value = "Job">Job</option><option value = "Piercings" >Piercings</option><option value = "Tattoos" >Tattoos</option><option value = "Vices" >Vices</option></select></td>' + 
            '<td><input type = "checkbox" name = "" /></td>' + 
            '<td class = "operations"><a href = "#" class = "save-link" onclick = "return save_tag_row(\'edit\', \'edit_tag_row_' + data.tag_id + '\');">Save</a> | <a href = "#" class = "cancel-link">Cancel</a></td>' + 
            '</tr>');
        }
    });
    return false;
}
/*Tags administration scripts ends*/

/*Tags autosuggester starts*/
function tagsAutosuggest(event, object, category) {
    $('.suggester').remove();
//    $(object).blur(function() {
        //setTimeout(function(){$('.suggester').remove();},200);
//    });
    
    if ((event.keyCode >= 65 && event.keyCode <= 90) || event.keyCode == 32 || event.keyCode == 8) {
        $.post(baseUrl + '/index/tags-autosuggest', {'value': $(object).val().split(',').pop(), 'category':category}, function(data) {
            var data = $.parseJSON(data);
            if (data == null)
                return;
            var values = '';
            var row = '';
            var count = 0;
            for (k in data) {
                if (data.hasOwnProperty(k)) {
                    if (count % 2 == 0)
                        row = 'even';
                    else
                        row = 'odd';
                    
                    /*if ($(object).val() == '' || $(object).val() == ',') {
                        var data_to_insert = data[k].name;
                    } else {
                        var element_values = $(object).val().split(',');
                        last_item = element_values.pop();
                        element_values.push(data[k].name);
                        var data_to_insert = element_values.join(', ');
                    }
                    if ($(object).val().indexOf(', ' + data[k].name) !== -1) {
                        values = values + '<p class = "' + row + '"><span onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val(\'' + data_to_insert + '\')">' + data[k].name + '</span><span class = "remover" onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val(\'' + $(object).val().replace(', ' + data[k].name, '') + '\'); $(\'.suggester\').remove();">x</span></p>';
                    }
                    else if ($(object).val().indexOf(data[k].name + ', ') !== -1) {
                        values = values + '<p class = "' + row + '"><span onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val(\'' + data_to_insert + '\')">' + data[k].name + '</span><span class = "remover" onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val(\'' + $(object).val().replace(data[k].name + ', ', '') + '\'); $(\'.suggester\').remove();">x</span></p>';
                    } else if ($(object).val().indexOf(data[k].name) !== -1) {
                        values = values + '<p class = "' + row + '"><span onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val(\'' + data_to_insert + '\')">' + data[k].name + '</span><span class = "remover" onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val(\'' + $(object).val().replace(data[k].name, '') + '\'); $(\'.suggester\').remove();">x</span></p>';
                    } else*/
                    var name = data[k].name.replace(/\</g, '&lt;').replace(/\>/g, '&gt;');
                    //values = values + '<p class = "' + row + '"><span onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val($(this).text()); $(\'.suggester\').remove();">' + name + '</span></p>';
                    values = values + '<p class = "' + row + '" onclick = "$(\'input[name=\\\'' + $(object).attr('name') + '\\\']\').val($(this).text()); $(\'.suggester\').remove();">' + name + '</p>';
                    count++;
                }
            }
            $(object).after('<div class = "suggester">' + values + '</div>');
        });
    }
    return false;
}

function tag_add(type, value) {
    if (value.length >= 3 && value.length <= 100) {
			$.post(baseUrl + '/index/banned-term',{'type':'tags', 'tag': value}, function(data) {
			var data = $.parseJSON(data);
			if(data != null )
			{
				if (data.action == "banned"){
		    		alert(value + " is a banned word. Shame on you!");
		    	} else { 
			    	$('input:[name="form[Edit][' + type + ']"]').val($('input:[name="form[Edit][' + type + ']"]').val() + ', ' + value);
			        $('#' + type + '-values').append('<span><b class = "remover" onclick = "return remove_tag(\'' + type + '\', \'' + value + '\', this);">x</b> ' + value + '&nbsp;&nbsp;</span>');
			        $('input:[name="form[Edit][' + type + '_adder]"]').val('');
		    	} 
			}
			}); 
    }
    return false;
}

function remove_tag(type, value, element) {
    var old_value = $('input:[name="form[Edit][' + type + ']"]').val();
    if (old_value.indexOf(', ' + value) !== -1)
        new_value = old_value.replace(', ' + value, '');
    else if (old_value.indexOf(value + ', ') !== -1)
        new_value = old_value.replace(value + ', ', '');
    else
        new_value = old_value.replace(value, '');
    $('input:[name="form[Edit][' + type + ']"]').val(new_value);
    $(element).parent().remove();
    return false;
}
/*Tags autosuggester ends*/

/*Banned Words Check*/
function checkBannedWords(badwords, type, value)
{
	// var badwords = ["fuck", "asshole", "shit"];
	// if($.inArray("fuck", badwords) > -1){
	// 	alert("found");
		// $("#badwrdmsg").text = value + "is a banned term!";
		// return false;
	// 
}


	
/*COTD chick management starts*/
$(document).ready(function() {
    $('#add-chick-input').keyup(function (event) {
        $('#addCotdQueue .suggester').remove();
        if ((event.keyCode >= 65 && event.keyCode <= 90) || event.keyCode == 32 || event.keyCode == 8) {
            $.post(baseUrl + '/photo/chick-autocomplite', {'value': $(this).val(), 'event':'editRelations'}, function(data) {
                var data = $.parseJSON(data);
                if (data == null)
                    return;
                var values = '';
                var row = '';
                var count = 0;
                for (k in data) {
                    if (data.hasOwnProperty(k)) {
                        if (count % 2 == 0)
                            row = 'even';
                        else
                            row = 'odd';
                        values = values + '<p onclick = "$(\'#add-chick-input\').val(\'' + data[k].chick_name + '\'); $(\'#addCotdQueue .suggester\').remove();" class = "' + row + '">' + data[k].chick_name + '</p>';
                        count++;
                    }
                }
                $('#add-chick-input').after('<div class = "suggester">' + values + '</div>');
            });
        }
        return false;
    });
});
/*COTD chick management ends*/

/*COTM Voting starts*/
function COTMVote(chick_id) {
    $.post(baseUrl + '/index/cotm-vote', {chick_id: chick_id}, function(data) {
        $('.chicks-nominee li input').remove();
        $('.chicks-nominee li').append('<p>Thank you for voting</p>');
        $('.chicks-nominee li #votes_for_' + chick_id + ' span').text(parseInt($('.chicks-nominee li #votes_for_' + chick_id + ' span').text()) + 1);s
    });
}
/*COTM Voting ends*/

/*COTY Voting starts*/
function COTYVote(chick_id) {
    $.post(baseUrl + '/index/coty-vote', {chick_id: chick_id}, function(data) {
        $('.chicks-nominee li input').remove();
        $('.chicks-nominee li').append('<p>Thank you for voting</p>');
        $('.chicks-nominee li #votes_for_' + chick_id + ' span').text(parseInt($('.chicks-nominee li #votes_for_' + chick_id + ' span').text()) + 1);
    });
}
/*COTY Voting ends*/

/*Home-page editing starts*/
//$(function() {
jQuery(document).ready(function() {
    $('#chick-featured-edit div .remover').live('click', function() {
        var chick_id = $(this).parent().attr('id').replace('chick-', '');
        var object = this;
        $.post(baseUrl + '/index/delete-from-featured', {chick_id: chick_id}, function() {
            $(object).parent().remove();
        });
    });
    $('#featured_chick_add_button').live('click', function () {
        var chick = $('#dialog #add-add-chick-input').val();
        $.post(baseUrl + '/index/add-to-featured', {chick: chick}, function(data) {
            if (data == 'false') {
                alert('Sorry, but this chick is already featured!');
                return false;
            }                
            if (data == 'too much') {
                alert('There can be only 12 featured chicks.');
                return false;
            }                
            if (data == 'deleted') {
                alert('This chick can\'t be featured since her profile is deleted.');
                return false;
            }                
            var data = $.parseJSON(data);
            $('#dialog #chick-featured-edit').append('<div id = "chick-'+data.page_id+'">'+chick+' <span class = "remover">X</span></div>');
        });
    });
    $('#hot_chicks .more').click(function() {
        if ($(this).text() == 'More ▼')
            $(this).text('Less ▲')
        else 
            $(this).text('More ▼')
        $("#lists-container-second").toggle('blind', {}, 500);
        return false;
    });
});
function back_to_previous(position, id, object) {
    $('#dialog #section-' + position + ' .preview').attr('src', $(object).attr('src'));
    $('#dialog #section-' + position + ' input[name="form[MainEdit][article]['+position+'][url]"]').val($(object).attr('url'));
    $('#dialog #section-' + position + ' input[name="form[MainEdit][article]['+position+'][title]"]').val($(object).attr('title'));
    $('#dialog #section-' + position + ' textarea[name="form[MainEdit][article]['+position+'][description]"]').val($(object).attr('description'));
    $('#dialog #section-' + position + ' input[name="form[MainEdit][article]['+position+'][previous]"]').val(id);
    return false;
}
/*Home-page editing ends*/

/* home carusel block */
var timer=0;
jQuery(document).ready(function() {
$('#home-carousel img').mousemove(function(e){$('#desc-box').css({left: e.pageX+10, top: e.pageY+10});});
$('#home-carousel img').mouseout(function(){$('#desc-box').hide();clearTimeout(timer);});
$('#desc-box .fon').css({opacity: 0.8});
});

function showdesc(id){
	$('#desc-box .text').html($('#desc_'+id).html());
	timer=setTimeout(function(){$('#desc-box').show();},2000);
}
var ti;
function show_previous(){
	ti=setTimeout(function(){
		$('#dialog #edit-home-bl').bind('click',function(e){
		if ($('#dialog .block-previous').is(':visible')){
			clearTimeout(ti);
			$('#dialog .block-previous').hide();
			$('#dialog #edit-home-bl').unbind('click');
		}
	},500);
	});
}
jQuery(document).ready(function() {
    $(".edit-home").bind('click', function() {
        $("#dialog").html($("#edit-home-content").html());
        $("#dialog").dialog({
            title: 'Edit Home Page',
            width: 1100,
            height: 600,
        });
        $('#dialog').dialog('open');
        
        $("#dialog .box1 input").each(function() {
            if (this.checked){
                $("#dialog .tabs").hide();
                var sel=this.value;
                $('#dialog #tab'+sel).show();
            }
            $(this).click(function() {
                if (this.checked){
                    $("#dialog .tabs").hide();
                    var sel=this.value;
                    $('#dialog #tab'+sel).show();
                }
            });
        });
        return false;
    });
    $('#dialog #add-add-chick-input').live('keyup', function (event) {
        $('#dialog .suggester').remove();
        if ((event.keyCode >= 65 && event.keyCode <= 90) || event.keyCode == 32 || event.keyCode == 8) {
            $.post(baseUrl + '/index/chick-autocomplite', {'value': $(this).val(), 'event':'featured'}, function(data) {
                var data = $.parseJSON(data);
                if (data == null)
                    return;
                var values = '';
                var row = '';
                var count = 0;
                for (k in data) {
                    if (data.hasOwnProperty(k)) {
                        if (count % 2 == 0)
                            row = 'even';
                        else
                            row = 'odd';
                        values = values + '<p onclick = "$(\'#dialog #add-add-chick-input\').val(\'' + data[k].chick_name + '\'); $(\'#dialog .suggester\').remove();" class = "' + row + '">' + data[k].chick_name + '</p>';
                        count++;
                    }
                }
                $('#dialog #add-add-chick-input').after('<div class = "suggester">' + values + '</div>');
            });
        }
        return false;
    });
});

function toggleUserLinks(divbox) {
    var boxes = new Array('register_box', 'login_box', 'profile_box');
    $('#register_box_two').hide();
    for (i = 0; i < boxes.length; i++) {
        if (boxes[i] != divbox) {
            $('#'+boxes[i]).hide();
            $('#'+boxes[i]).parent().children('a').removeClass('current');
        }
    }
    $('#'+divbox).toggle();
    $('#'+divbox).parent().children('a').toggleClass('current');

    if ($('#'+divbox).css('display') == 'none') {
        $('#homepage_right_ad').css('display', 'block');
        $('#main_top_ad').css('display', 'block');
    } else {
        $('#homepage_right_ad').css('display', 'none');
        $('#main_top_ad').css('display', 'none');
    }
}
/* home carusel block ends */

/*COTM|COTY|COTD description editing starts*/
function editDescription(id, period, object) {
    var old_description = $(object).prev().text();
    $('#dialog').html('<div class = "input textarea"><textarea id = "description" cols = "49" rows = "7">' + old_description + '</textarea></div>');
    $('#dialog').dialog({
        title: 'Edit description',
        buttons: {
            "Save": function() {
                $.post(baseUrl + '/index/save-description', {id: id, period: period, description: $('#description').val()}, function(data) {
                    $(object).prev().text($('#description').val());
                    $('#dialog').dialog("close");
                });
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });
    $('#dialog').dialog('open');
    return false;
}
/*COTM|COTY|COTD description editing ends*/

/*Featured chicks more link starts*/
$(function() {
    $('#featured_chicks #more-featured').toggle(function () {
        $('#featured_chicks #more-featured').text('◄ Previous');
        $('#featured_chicks .first-list').hide();
        $('#featured_chicks .second-list').fadeIn(300);
    }, function() {
        $('#featured_chicks #more-featured').text('More ►');
        $('#featured_chicks .second-list').hide();
        $('#featured_chicks .first-list').fadeIn(300);
    });
    /*$('#featured_chicks #more-featured').click(function() {
        $('#featured_chicks #more-featured').toggle($('#featured_chicks #more-featured').text('aaa'), $('#featured_chicks #more-featured').text('bbb'));
        return false;
    });*/
});
/*Featured chicks more link ends*/

/*Search block starts*/
$(function() {
    $('#search-query').focus(function() {
        if ($(this).val() == 'search')
            $(this).val('');
    });
    $('#search-query').blur(function() {
        if ($(this).val() == '')
            $(this).val('search');
    });
});

$(function() {
    /*User profile scripts*/
    $('#nuke-activity').click(function () {
        $('#dialog').html('<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure, that we should remove all activity of this user?');
        $('#dialog').dialog({
            title: 'Nuke all activity?',
            buttons: {
                "Yes": function() {
                    $('#NukeActivity').submit();
                },
                "No": function() {
                    $('#dialog').dialog("close");
                }
            }
        });
        $('#dialog').dialog('open');
        return false;
    });
    
    $('.activity .pager li a').live('click', function () {
        var user_name = $('.activity').attr('title');

//        if ($('.activity .pager li a').attr('href').substr(-1, 1) == '/')
//            var page = $('.activity .pager li a').attr('href').slice(0, -1).split('/').pop();
//        else
//            var page = $('.activity .pager li a').attr('href').split('/').pop();
        
        var page = $(this).text();
        if (!parseInt(page))
        	var page = $(this).attr('href').slice(0, -1).split('/').pop();
        
        if (!parseInt(page))
            page = 1;
            
        $.post(baseUrl + '/user/' + user_name + '/' + page + '/', {pagination: true}, function(data) {
            $('.activity').html(data);
        });
        
        return false;
    });
    /*User profile scripts*/
    /*User management scripts*/
    $('.ban-unban').click(function() {
        var user = $(this).attr('title');
        var old_role_id = $(this).attr('prev_role');
        $('.unban-' + $(this).attr('title')).parent().text('☼ Unbanned');
        $.post(baseUrl + '/manage-users/', {unban: true, user: user, old_role_id: old_role_id});
        return false;
    });
    /*User management scripts*/
    
    
    /* Edit Chick Page */
	// $('#ChickEditForm').submit(function(event) {
    $('.submitButton').click(function(){
    	var nickname = $('#editNickname').val();
		var birthname = $('#editBirthname').val();
		var hometown = $('#editHometown').val();
		var bodyEditor = $('textarea#editor').val();
		// check the banned terms 
			$.post(baseUrl + '/index/banned-term',{'type':'names','nickname': nickname, 'birthname': birthname, 'hometown': hometown, 'editor': bodyEditor}, function(data) {
				var data = $.parseJSON(data);
				if(data != null )
				{
					if (data.action == "banned"){
			    		alert("Please don't submit banned terms!");
						return false;
					} else {
						$('#ChickEditForm').submit();
					}
				}
				});
		return false;
	});

    
    
    /*Banned terms*/
    $('#AddTerms').click(function() {
       
        if ($('.add_term textarea').val() == '') {
            alert('Please enter a term to ban.');
            return false;
        }
        $.post(baseUrl + '/banned-terms/', {type: 'add', terms: $('.add_term textarea').val()}, function (data) {
            var data = $.parseJSON(data);
            if (data == null) {
                    return;
            }
        
            for (var i = 0; i <= data.length; i++) {
                
                if (typeof(data[i]) !== 'undefined') {
                    $('#terms-list').append('<tr><td>' + data[i] + '</td><td><span class = "remover">x</span></td></tr>');
                    $('.add_term textarea').val('');
                }         
            }
        });
        return false;
    });
    
    $('#terms-list .remover').live('click', function() {
        var term = $(this).parent().prev().text();
        $(this).parent().parent().remove();
        $.post(baseUrl + '/banned-terms/', {type: 'delete', term: term});
        return false;
    });
    /*Banned terms*/
    
});

