var map_object;
var rollover_callback_handle_id;
var MAX_COMMENT_LENGTH = 100;
var MAX_IMAGE_WIDTH = 150; 
var MAX_IMAGE_HEIGHT = 150;

var DEFAULT_IMAGE_WIDTH = 640;
var DEFAULT_IMAGE_HEIGHT = 480;

var DEFAULT_URL_LINK = 'insert URL here...';

var uploader_file_exist = 0; //file, added to flash-uploader
var files_to_post = ''; //file, added to flash-uploader

var post_button_disabled = false;
var AJAX_POST_COMMENT_TIMEOUT = 3000; // in millisec.

var FLASH_OFFSET = 28;

var close_share = 1;;
var scale_image = function(img)
{
    var cont_width = DEFAULT_IMAGE_WIDTH;
    var cont_height = DEFAULT_IMAGE_HEIGHT;
    
    var o_w = $(img).width();
    var o_h = $(img).height();
    
    var k_w = 0;
    var k_h = 0;
    
    k_w = o_w / cont_width;
    k_h = o_h / cont_height;

    if(k_w > 1 || k_h > 1)
    {
        if(k_w > k_h)
            $(img).css({width: (o_w / k_w)+'px', height: (o_h / k_w)+'px'});
        else
        if(k_h > k_w )
            $(img).css({width: (o_w / k_h)+'px', height: (o_h / k_h)+'px'});
    }
    else
        $(img).css({width: o_w + 'px', height: o_h +'px'});
    
    $(img).css({display: 'inline'});
}

function checkmessage(e)
{
    var message = $('#commenttext').val();
    
    if (message.length >= MAX_COMMENT_LENGTH)
    {
        message = message.substring(0, MAX_COMMENT_LENGTH);
        $('#commenttext').val(message)
    }
    $('#charsleft').html(MAX_COMMENT_LENGTH - message.length);
}

var view_comments = function(page, cid) {
    
    var opts = {g: IMAGE};
    if (page)
        opts['page'] = page;
    if (cid)
        opts['cid'] = cid;
        
    var image = param(document.location.href, 'g');
    var via = param(document.location.href, 'via');
    
    if(image)
        opts['g'] = image;
    if(via)
        opts['via'] = via;
        
    opts['r'] = Math.random();
    opts['via'] = 'tfrog';

    posting_loader(true);       
    $.post('/gallerycomments.php', opts, function (o) {
        o = '<span>' + o + '</span>';
        $('#Comments').html('');
        
        $('#Comments').append($(o).html());

        check_replies();    
                
        posting_loader(false);
    }, 'html');

}

function view_replies(obj)
{
    var insiders = $(obj).parent().parent().parent().find('> .insider:visible');
    if($(insiders).size() == 0)
    {
        $(obj).html($('#hide_replies').val());
        $(obj).parent().parent().parent().find('> .insider:invisible').show();
    }
    else
    {
        $(obj).html($('#show_replies').val());
        $(insiders).hide();
    }
}

function check_replies()
{
    $.each($('#Comments .comment-open'), function(i, o){
        if($(o).parent().parent().find('.insider').size() > 0)
        {
            $(o).show();    
        }
    })    

}

function posting_loader(flag) {
    if(flag) {
        post_button_disabled = true;
        $('#post_comment').html('Posting...');
        $('#loader').show();
    } else  {
        post_button_disabled = false;
        $('#post_comment').html('&nbsp;&nbsp;&nbsp;Post&nbsp;&nbsp;&nbsp;');
        $('#loader').hide();
    }        
}

function logger(time_in, url_image_path){
    var currentTime1 = new Date();
    var pass_time = currentTime1.getTime();
    var done_time = pass_time - time_in; 
    rlog = new Image();
        rlog.src = "http://img1.imageshack.us/rt_load/?t=" + done_time + "&f=" + url_image_path ;

}

var start = 0;

function get_bitly( ){
    $.getJSON('/bitlyapi.php?func=ajax&link='+short_url+'&path='+short_path, function(response) {
      if (!response.errno) {
    document.getElementById('bitly_new_link').value = response.link;
    $('#new_link_bitly').show();
    $('#click_bitly').hide();
        //$('div#user_widget').show();
      }
    });
}

function add_fav( )
{
    $.getJSON('/make_favorite.php?func=ajax&type=album&image='+IMAGE+'&server='+SERVER+'&shortl='+SHORTL+'&poster='+POSTER , function(response) {
      if (!response.errno) 
      {
	    if(response ==1 )
	    {	
          $("#favorite_choose #heart").attr("src", "http://imageshack.us/images/red_heart.png");
          $("#favorite_choose").attr("onmouseout", "");
          $("#favorite_choose").attr("onclick", "");
	    }
	    if(response == 0)
	    {
          document.getElementById('favorite_choose').innerHTML='<span style="margin-left:4px;">Please <a href="http://yfrog.com/froggy_login.php">sign in</a> first.</span>';
	        document.getElementById('loader_ajax').style.display='none';
          document.getElementById('favorite_choose').style.display='';	
        }
      }
    });
}

function add_like()
{
    $.getJSON('/make_like.php?func=ajax&type=album&image='+IMAGE+'&server='+SERVER+'&shortl='+SHORTL+'&poster='+POSTER , function(response) {
        if (!response.errno) 
            {
            if(response ==1 )
            {	
              $("#like_choose #heart").attr("src", "/images/btn-like-red.gif");
              $("#like_choose").attr("onmouseout", "");
              $("#like_choose").attr("onclick", "");
            }
            if(response ==0 )
            {
                document.getElementById('favorite_choose').innerHTML='<span style="margin-left:4px;">Please <a href="http://yfrog.com/froggy_login.php">sign in</a> first.</span>';
                document.getElementById('loader_ajax').style.display='none';
                document.getElementById('favorite_choose').style.display='';	
            }
        }
    });
}
  
function post_rate( star ){
    if(POSTER == ''){
      var get_post = '/twitter_ajax_post.php?func=post_rating&message=Just rated this '+SHORTL+' '+ star  +' / 5 stars on %23yfrog';
    }
    if(POSTER != ''){
      var get_post = '/twitter_ajax_post.php?func=post_rating&message=@'+POSTER+' posted this '+SHORTL+' on %23yfrog and I rated it '+ star +' / 5 stars.';
    }

    $.getJSON(get_post , function(response) {
      if (!response.errno) {
        if(response ==1 ){
//	alert('success');
        }
        if(response ==0 ){
//	alert('fail');
        }

      }
    });
}

function ajax_post_comment( comment_post ){
    var get_post = '/twitter_ajax_post.php?func=post_comment&message=' + comment_post;

    $.getJSON(get_post , function(response) {
      if (!response.errno) {
        if(response ==1 ){
    //      alert('success');
        }
        if(response ==0 ){
    //      alert('fail');
        }

      }
    });
}



var tr_marker = 0; // Total related marker
var new_row = new Array();

function image_hider(image_id, check_num, block_hider)
{
    var i_scale2 = function(o, w, h) {
        var rect = get_scaled_size(o.width, o.height, w, h, false);
        $(o).css({
            'width': rect[0],
            'height': rect[1],
            'padding-top': Math.ceil((h - rect[1]) / 2),
            'padding-left':0});
        };
    tr_marker++;
    if(tr_marker < 32){	
        new_row = RELATED_IMAGES[tr_marker];
        var img = $('<img>').bind('load', function() {
            if(this.width<=1 || this.height<=1){
                this.style.display='none';
                image_hider("rtmp" + check_num , check_num,  "grey" + check_num  );
            }
            i_scale2(this, 100, 72);
            $('#rel' + check_num + ' a').append($(this));
        }).attr({'src': unescape('http://triton.imageshack.us/H' + new_row[0] + '/scaled.php?tn=1&server=' + new_row[3] + '&filename=' + new_row[2] + '&xsize=100&ysize=100'), 'id' : 'rtmp' + i });
    }	
    return;
}

/* functions for flash-uploader  BEGiN*/
function uploadstart()
{
    var o = document.getElementById('uploader');
    posting_loader(true);
    o.SetVariable('go', '1');
}

function uploaderror(args)
{
    posting_loader(false);
}

function uploadcomplete(args)
{
    posting_loader(true);
    files_to_post = args;
    uploader_file_exist = 0;
    post_button_disabled = false;
    $("#post_comment").click();
}

function uploadcancel()
{
    posting_loader(false);
}

function browse_click() 
{
}

function cancel_click() 
{
}

function file_added(n,k) 
{
    uploader_file_exist = k;
    $("#comments").css('height', 100 + FLASH_OFFSET + 'px');
}

function file_removed(n,k) 
{
    uploader_file_exist = k;
    if(k == 0)
        $("#comments").css('height','100px');
    
}

function save_panel_state(o) {
    var state = $.cookie('gpanel');
    if (!state || state.length != 6) {
        state = '110001';
    }
    var pos = parseInt(o.attr('state'));
    if (pos >= state.length)
        return;
    var s = '0';
    if (o.attr('className').indexOf('activeaccordion') >= 0)
        s = '1';
    state = state.substr(0, pos) + s + state.substr(pos + 1);
    $.cookie('gpanel', state, 365, '/'); 
}

function save_panel_state(o) {
    var state = $.cookie('gpanel');
    if (!state || state.length != 2) {
        state = '01';
    }
    var pos = parseInt(o.attr('state'));
    if (pos >= state.length)
        return;
    var s = '0';
    if (o.attr('className').indexOf('activeaccordion') >= 0)
        s = '1';
    state = state.substr(0, pos) + s + state.substr(pos + 1);
    $.cookie('gpanel', state, 365, '/'); 
}

$(document).ready(function() 
{
    $('#uploader_action').click(function(e) 
    {
        var t = $(this);
        if($('#upflash:visible').size() == 0)
        {
            $("#comments").css('height','100px');
            t.css('cursor', 'default');
            t.find("span").html('');
            $('#upflash').show();
        }
    })
    
    $('.accordionheader').click(function(e) {
        var t = $(this);
        $('#' + t.attr('panel')).toggleClass('hidden');
        t.toggleClass('activeaccordion');
        save_panel_state(t);
    })
    
    
    $('li.thetoplink').hover(
      function() { $('ul', this).css('display', 'block'); },
      function() { $('ul', this).css('display', 'none'); }
    );  

    $(".comment_action").bind('click', function(){

        if($('.commentbox_item:visible').size() > 0)
        {
            $('.commentbox_item').hide();
            $("img.comment_action").attr('src', 'http://imageshack.us/images/new_right_arrow.png');
            $('#comment_thewhitebottom').hide();
            $('#comment_thebluebottom').show();
        }
        else
        {
            $('.commentbox_item').show();
            $("img.comment_action").attr('src', 'http://imageshack.us/images/new_down_arrow.png');
            $('#comment_thewhitebottom').show();
            $('#comment_thebluebottom').hide();
        }
    });
 
     $('.image-info-tab').bind('click', function(e) {
        var o = $(this);
        var id = o.attr('id');
        var linkedId = id.substring(0, id.length - 6);
        if (o.hasClass('active')) {
            o.addClass('non-active').removeClass('active');
            $('#' + linkedId).hide();
        } else {
            o.addClass('active').removeClass('non-active');
            $('#' + linkedId).show();
        }
    });
    
    $('.readonly').bind('click', function(e) {
        $(this).focus().select();
        e.stopPropagation();
        e.preventDefault();
    });
    
    $('#hide-map a').bind('click', function(e) {
        $('#hide-map').hide();
        $('#show-map').show();
        $('#map').hide();
        e.stopPropagation();
        e.preventDefault();
    });
    
    $('#show-map a').bind('click', function(e) {
        $('#hide-map').show();
        $('#show-map').hide();
    
        if (!map_object) {
            if (GBrowserIsCompatible()) {
                $('#map').show();
                map_object = new GMap2($('#map').get(0));            
                map_object.setUIToDefault();
                var point = new GLatLng(parseFloat(GEO[0]), parseFloat(GEO[1]));
                map_object.addOverlay(new GMarker(point));
                $(document).bind('unload', function() {
                    GUnload();
                });
            }
        }
        if (GBrowserIsCompatible()) {
            $('#map').show();
            map_object.setCenter(new GLatLng(parseFloat(GEO[0]), parseFloat(GEO[1])), 13);
        }
        e.stopPropagation();
        e.preventDefault();
    });
    

    $('#post_comment').bind('click', function(e) 
    {
        if(post_button_disabled)
            return false;
        
        posting_loader(true);
        
        var params = collect_params(e);
        if(!params)
            return false;
        
        if(uploader_file_exist > 0)
            uploadstart();
        else
        {
            if($.cookie('YFOTOKEN'))
            {
                
                // start comment posting
                posting_loader(true);
                $("#comment-error").hide();
                
                if(POSTER != '')
                    ajax_post_comment(params.text + ' (@' + POSTER + ')' + SHORTL  );
                
                $.ajax({
                    timeout: AJAX_POST_COMMENT_TIMEOUT,
                    url: '/addcommentgallery.php', 
                    type: 'POST',
                    data: {
                            g:params.g, 
                            text:params.text, 
                            attached_files:params.attached_files, 
                            reply_to_id:params.reply_to_id, 
                            poster:POSTER,
                            reply_to_href:params.reply_to_href,
                            json:true
                    },
                    success: function(o) {
                        if(o.status != 0)
                        {
                            posting_loader(false);
                            alert($.trim($('#comment-error-' + o.status + ' span').html()));
                            return false;
                        }
                        
                        posting_loader(false);
                        
                        $('#commenttext').val('');
                        $('#charsleft').html(MAX_COMMENT_LENGTH);
                        view_comments(1, null);
                        return true;
                    },
                    error: function(){
                        posting_loader(false);
                        alert($.trim($('#comment-error-4 span').html()));
                    },
                    dataType: 'json'
                });    
                
                e.stopPropagation();
                e.preventDefault();
            }
            else
            {
                $("#comment-error").hide();
                // first - forward user to twitter, and post comment
                $.post('/comments_twitter_post.php', 
                    {
                            g:params.g, 
                            text:params.text,
                            poster:POSTER, 
                            attached_files:params.attached_files, 
                            json:true, 
                            reply_to_id:params.reply_to_id,
                            reply_to_href:params.reply_to_href,
                            return_to: document.location.href
                    },
                    function(o)
                    {
                        posting_loader(true);
                        if(o.error)
                        {
                            posting_loader(false);
                            alert($.trim($('#comment-error-' + o.status + ' span').html()));
                            return false;
                        }
                        else
                            document.location.href = o.status;
                    },
                    'json'
                );
                e.stopPropagation();
                e.preventDefault();
            }
        }
    
    });
    
    $('.comment_reply').live('click', function(e) {
        var el = e.target;
        if($(el).attr('class') == 'comment_reply')
            $('#is_reply_to').val($(el).attr('id'));
    
        e.stopPropagation();
        e.preventDefault();
    });
    
    $('.comment_delete').live('click', function(e) {
        
        $.post('/deletecommentgallery.php', {json:true,g:IMAGE,id:$(this).attr('id').substring(2)}, function(o) {
            if (o.status) {
                view_comments(1, null);
            }
        }, 'json');
        e.stopPropagation();
        e.preventDefault();
    });


    
  
   
    var collect_params = function(e){
        var params = null;
        var text = jQuery.trim($('#commenttext').val());
        var reply_to_id = jQuery.trim($("#is_reply_to").val()).substr(2);
       
        if(text.length > MAX_COMMENT_LENGTH)
        {
            alert($('#error_too_log_comment').val() +" ("+text.length+" )");
            return false;
        }
        if (!text.length) 
        {
            alert($('#error_empty_comment').val());
            return false;
        }
    
        params = {
            g:          IMAGE, 
            text:           text, 
            attached_files: files_to_post, 
            reply_to_id:    reply_to_id, 
            reply_to_href:  escape(jQuery.trim($("#link_to_"+reply_to_id).val())),
            return_to:      document.location.href
        }
        
        files_to_post = '';
        return params;
       
    }

    var get_scaled_size = function (width, height, max_width, max_height)
    {
        if (width <= max_width && height <= max_height)
            return [width, height];
    
        height *= 1.0;
        width  *= 1.0;
        k = Math.min(max_width/width, max_height/height);;
        w = Math.floor(width * k);
        h = Math.floor(height * k);
        if (w == 0)
            w = 1;
        if (h == 0)
            h = 1;
        return [w, h];
    }
   
    $.each($('.thumb-cmnt'), function(i, o){
        if($(o).width() > MAX_IMAGE_WIDTH || $(o).height() >  MAX_IMAGE_HEIGHT)
        {
            var new_size = get_scaled_size($(o).width(), $(o).height(), MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT );
            $(o).width(new_size[0]);
            $(o).height(new_size[1]);
        }
    })
    
    if($('#backup_server_url').size() != 0)
    {
        var img = new Image();
        $(img).hide();
        
        if($('#via').val() == 'blue')
            $(img).bind('click', function(){ self.location.href=$('#backup_server_url').val(); pageTracker._trackEvent($('#track_event').val(),'full_image_click')});
            
        $(img).bind('load', function() {scale_image(this)});
        
        img.className = 'border';
        img.alt = $('#backup_server_filename').val();
        img.src = $('#backup_server_url').val();
        img.id  = "main_image";

        if($('#via').val() != 'blue' && $('#via').val() != 'ifs')
        {
            $('#main').html('<div style="cursor:pointer;" onclick="window.open(href=\''+$('#backup_server_url').val()+'\')" ></div>');
            $('#main > div').append(img);
            
            $('#rotator_left').bind('click', function(){
                rotator('left', $('#main_image').width(), $('#main_image').height(), $('#backup_server_url').val() , start); 
                if(start ==0)
                    start = 1; 
                else
                    start=0;
                pageTracker._trackEvent($('#track_event').val(),'rotate_left');
            })
            
            $('#rotator_right').bind('click', function(){
                rotator('right', $('#main_image').width(), $('#main_image').height(), $('#backup_server_url').val(), start ); 
                if(start ==0)
                    start = 1;
                else
                    start=0;
                pageTracker._trackEvent($('#track_event').val(),'rotate_right');
            })
        }
        else
            $('#main').append(img);
    }
   
    //if ($('#Comments comment-box').size() == 0)
    //    view_comments(1, null);   

//    if ($('#kws').val() == '1') {
//        $('.affinity-ads').load('/affinity.php', {q: $('#searchfield').val(), i: IMAGE}).show();
//    }

        posting_loader(false);
});


function share_this_arrow()
{
    if( close_share == '0' ||  close_share == 'undefinded' ){
        document.getElementById('share_arr').src='/images/opened_arrow.gif'; 
        document.getElementById('share_area').style.display='';  close_share = '1'; 
        var done='1';
    }
    if(close_share == '1' && done != '1'){
        document.getElementById('share_arr').src='/images/closed_arrow.gif';  
        document.getElementById('share_area').style.display='none'; close_share = '0';}
        done ='0';
}
 
function param(qs, name)
{
    if (!qs)
        return null;
    var params = qs.split(/[&?]/);
    for (var p = 0; p < params.length; p++)
    {
        var tokens = params[p].split('=');
        if (tokens.length == 2 && tokens[0] == name)
            return tokens[1];
    }
    return null;
}

