var App = window.App || {};

/** We will put all of our variables and resources (URL-s, listings etc) **/
App.data = {
  'keep_alive_interval' : 1140000,
  'refresh_session_url' : '/session/renew',
  'indicator_url' : '/img/ajax/indicator.gif',
  'indicator_big_url' : '/img/ajax/indicator_big.gif'
};

// All widgets should be defined here
App.widgets = {};

App.dialog = function(message, url, callback){
  // TODO: Create modal dialog for dialog box
} // App.dialog

/**
 * Send post request to specific link
 *
 * @param string the_link
 */
App.post = function(the_link, fields) {
  var default_fields = [{
    'type'  : 'hidden',
    'name'  : 'submitted',
    'value' : 'submitted'
  }];

  post_fields = jQuery.merge(default_fields, fields);
  
  var form = $(document.createElement('form'));
  form.attr({
    'action' : the_link,
    'method' : 'post'
  });
  
  jQuery.each(post_fields, function(key, field_attr) {
    var field = $(document.createElement('input'));
    
    field.attr(field_attr);
    
    form.append(field);  
  });
  
  $('body').append(form);

  form.submit();
  return true;
};

/**
 * Send post request to specific link
 *
 * @param string the_link
 */
App.get = function(the_link, fields) {
  var default_fields = [{
    'type'  : 'hidden',
    'name'  : 'submitted',
    'value' : 'submitted'
  }];

  post_fields = jQuery.merge(default_fields, fields);
  
  var form = $(document.createElement('form'));
  form.attr({
    'action' : the_link,
    'method' : 'get'
  });
  
  jQuery.each(post_fields, function(key, field_attr) {
    var field = $(document.createElement('input'));
    
    field.attr(field_attr);
    
    form.append(field);  
  });
  
  $('body').append(form);
  
  form.submit();
  return true;
};

App.confirm = function(msg){
  return confirm(msg);  
} // confirm

/**
 * Convert & -> &amp; < -> &lt; and > -> &gt;
 *
 * @param str
 * @return string
 */
App.clean = function(str) {
  if(typeof(str) == 'string') {
    str = str.replace(/&/g, '&amp;');
    str = str.replace(/\>/g, '&gt;');
    str = str.replace(/\</g, '&lt;');
  }
  
  return str;
};

/**
 * Convert MySQL formatted datetime string to Date() object
 *
 * @params String timestamp
 * @return Date
 */
App.mysqlToDate = function(timestamp) {
  var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
  var parts=timestamp.replace(regex, "$1 $2 $3 $4 $5 $6").split(' ');
  return new Date(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]);
};

// Do stuff that we need to do on every page...
$(document).ready(function() {
  App.layout.init();
  App.layout.init_qtip();
//  App.layout.init_blog_thumbs();
  App.RefreshSession.init();
  App.PrintPreview.init();
});

/** Layout **/
App.layout = function() {
  
  // Result
  return {
  
    /**
     * Initialize layout
     */
    init : function() {
      // Flash
      $('#success, #error').click(function() {
        $(this).hide('fast');
      });
      
//      // Hoverable
//      $('.hoverable').hover(function() {
//        $(this).addClass('hover');
//      }, function() {
//        $(this).removeClass('hover');
//      });
//
        // Hoverable
        $('.focusable').click(function() {
            $('.focusable').removeClass('focus');
            $(this).addClass('focus');
        });
      
      // Hide question mark if we don't have tips on page
      if($('#tip').length && $('#tip').hasClass('hidden')) $('#tip a[name=hide]').trigger('click');
     
    },
    
    /**
     * Initialize qtip for entaglement
     */
    init_qtip : function() {
       $('.entaglement').click(function(){
       });
      
       $('.entaglement, .tooltip').tipsy({gravity: 's'})
    },
    /**
     * Initialize qtip for entaglement
     */
    init_blog_thumbs : function() {
      $('a.blog_thumb').each(function()
      {
        blog_id = $(this).attr('id');
        // Create image content using websnapr thumbnail service
        var content = '<img src="http://' + document.domain + '/thumbs/blogs/' + blog_id + '.png"';
        content += '" alt="Loading thumbnail ..." height="127" width="160" />';
        
        // Setup the tooltip with the content
        $(this).qtip(
        {
           content: content,
           position: {
              corner: {
                 tooltip: 'bottomMiddle',
                 target: 'topMiddle'
              }
           },
           style: {
              tip: true, // Give it a speech bubble tip with automatic corner detection
              name: 'cream'
           }
        });
      });

    },
    
    /**
     * Init star unstar link
     *
     * @param string id
     * @return null
     */
    init_star_unstar_link : function(id) {
      $('#' + id).click(function() {
        var link = $(this);
        var parent = link.parent();
      
        // Block additional clicks
        if(link[0].block_clicks) {
          return false;
        } else {
          link[0].block_clicks = true;
        } // if
        
        var img = link.find('img');
        var old_src = img.attr('src');
        
        img.attr('src', App.data.indicator_url);
        
        $.ajax({
          url     : App.extendUrl(link.attr('href'), {async : 1}),
          type    : 'POST',
          data    : {'submitted' : 'submitted'},
          success : function(response) {
            parent.empty();
            parent.append(response);
          },
          error   : function() {
            img.attr('src', old_src);
          }
        });
        
        return false;
      });
    },
    
    init_submenu_items: function() {
      $("#sub_menu  a").click(function(){
        var link = $(this);
        var parent = link.parent();
        var content   = $('#content');
        var indicator = '<p class="indicator"><img src="' + App.data.indicator_big_url +'" alt="" /></p>';
          
        $("#sub_menu a").each(function(){
          if(link.html() !== $(this).html()){
            $(this).parent().removeClass('active');
          }
        });
        
        if(!parent.hasClass('active')){
          parent.addClass('active');
        } // if
        
        var old_content = content;
      
        content.empty();
        content.append(indicator);
        
        setTimeout(function() {  
          $.ajax({
            url     : link.attr('href'),
            type    : 'GET',
            data    : {'skip_layout' : 'true'},
            success : function(response) {
              content.empty();
              content.append(response);
            },
            error   : function() {
              content.append(old_content);
            }
          });
        }, 200);
        
        return false;
      });
      
    } // init_submenu_items
  } // init
}();

/**
 * Print preview module
 */
App.PrintPreview = function() {
  
  // Return value
  return {
    
    /**
     * Initialize print preview behavior
     *
     * @param void
     * @return null
     */
    init : function() {
      $('#print_button').click(function(e) {
        App.PrintPreview.open();
        e.stopPropagation();
        return false;
      });
      
      $('#print_preview_header #print_preview_close').click(function() {
        App.PrintPreview.close();
        return false;
      });
      
      $('#print_preview_header #print_preview_print').click(function() {
        window.print();
        return false;
      });
    },
    
    /**
     * Show print preview view
     *
     * @param void
     * @return null
     */
    open : function() {
      $('#style_main_css').attr('href', App.data.style_print_preview_css);
      $('#style_theme_css').attr('href', '');
    },
    
    /**
     * Close print preview view
     *
     * @param void
     * @return null
     */
    close : function() {
      $('#style_main_css').attr('href', App.data.style_main_css);
      $('#style_theme_css').attr('href', App.data.style_theme_css);
    }
    
  };
  
}();

// Refresh session requests
App.RefreshSession = function() {
  
  /**
   * Interval object used to call refresh function
   */
  var refresh_interval = null;
  
  // Return value
  return {
    
    /**
     * Initialize refresh interval
     *
     * @params void
     * @return void
     */
    init : function() {
      if(App.data.keep_alive_interval > 0) {
        refresh_interval = setInterval('App.RefreshSession.refresh()', App.data.keep_alive_interval);
      } // if
    }, // init
    
    /**
     * Function used to refresh session
     *
     * @param void
     * @return null
     */
    refresh : function() {
      $.ajax({
        url : App.data.refresh_session_url
      });
    } // refresh
  } // return
  
}(); // App.RefreshSession

// Change home page tagline
App.ChangeHomeTagline = function() {
	return {
	  init: function() {
	    $('#slogan .inner').each(function() {
	      $(this).css('display', 'block');
	      $(this).children('.line').css('padding-top', 322/2 - $(this).children('.line').height() / 2 + 'px');
	      $(this).css('display', 'none');
	    });
	    $('#slogan .inner:first').css('display', 'block');
      setTimeout('App.ChangeHomeTagline.change()', 8000);
	  },
    change: function() {
      $.ajax({
        url : '/tagline',
        type : 'POST',
        data : {'change' : 'change'},
        success : function(response) {
          if($('#slogan .inner:eq(2)').length) {
            setTimeout('App.ChangeHomeTagline.change()', 8000);
            $('#slogan .inner:first').fadeOut(250, function() {
              $(this).remove();
              $('#slogan .inner:first').fadeIn(500, function() {
                $('#slogan').append(response);
                $('#slogan .inner:last .line').css('padding-top', (322/2-$('#slogan .inner:last').height()/2) + 'px');
              });
            });
          }
        },
        error : function() {}
      });
    }
	}
}(); // App.ChangeHomeTagline

// Vote
App.vote = function() {
    return {
        init: function() {
        },
        up: function(type, type_id) {
            $('a#thumbup_' + type_id).blur();
            $('#thumbup_' + type_id).attr('href', 'javascript:void(0);').children('img').attr('src', '/img/thumbup_gray.gif');
            $('#thumbdown_' + type_id).attr('href', 'javascript:void(0);').children('img').attr('src', '/img/thumbdown_gray.gif');
            $.ajax({
                url : '/vote',
                type : 'POST',
                data : {'value': 'up', 'type': type, 'type_id': type_id},
                success : function(response) {
                    if(response == 'voted') return false;
                    response = response.split(':');
                    if(response[0] == 'login') window.location = response[1];
                    else $('#up_votes_' + type_id).html(response[1]);
                },
                error : function() {}
            });
        },
        down: function(type, type_id) {
            $('a#thumbdown_' + type_id).blur();
            $('#thumbup_' + type_id).attr('href', 'javascript:void(0);').children('img').attr('src', '/img/thumbup_gray.gif');
            $('#thumbdown_' + type_id).attr('href', 'javascript:void(0);').children('img').attr('src', '/img/thumbdown_gray.gif');
            $.ajax({
                url : '/vote',
                type : 'POST',
                data : {'value': 'down', 'type': type, 'type_id': type_id},
                success : function(response) {
                    if(response == 'voted') return false;
                    response = response.split(':');
                    if(response[0] == 'login') window.location = response[1];
                    else $('#down_votes_' + type_id).html(response[1]);
                },
                error : function() {}
            });
        }
    }
}(); // App.vote

// Tips
App.tips = function() {
  
    return {

        init: function() {
            // Hide click handler
            $('#tip a[name=hide]').click(function() {
                $.ajax({
                    url : '/tips',
                    type : 'POST',
                    data : {'type': 'hide'},
                    success : function(response) {
                        $('#tip').addClass('hidden');
                        $('#tabs ul').append('<li><a href="javascript:void(0);" onclick="App.tips.show(this);"  title="Show tips for current section"><span><b>?</b></span></a></li>');
                    },
                    error : function() {}
                });
	    });
        },
	  
        show: function(element) {
            if($('#tip').length) $('#tip').removeClass('hidden');
            $(element).remove();
        }
    
    }
}(); // App.Tips

// Favorite
App.favorite = function() {

    return {

        toggle: function(type, type_id) {
            $('a#favorite_' + type + '_' + type_id).blur();
            $.ajax({
                url : '/favorite',
                type : 'POST',
                data : {'type': type, 'type_id': type_id},
                success : function(response) {
                    if(response == 'removed') {
                        if (location.href.toString().indexOf('favorites') != -1) window.location = location.href;
                        else {
                            $('#favorite_' + type + '_' + type_id).attr('title', 'Add to favorites').html('Add to favorites');
                        }
                    } else if(response == 'added') {
                        $('#favorite_' + type + '_' + type_id).attr('title', 'Remove from favorites').html('Remove from favorites');
                    } else window.location = response;
                },
                error : function() {}
            });
        }

    }
	
}(); // App.Favorite

// Follow
App.follow = function() {

    return {

        toggle: function(type, type_id) {
            $('a#follow_' + type + '_' + type_id).blur();
            $.ajax({
                url : '/follow',
                type : 'POST',
                data : {'type': type, 'type_id': type_id},
                success : function(response) {
                    if(response == 'removed') {
                        if (location.href.toString().indexOf('following') != -1) window.location = location.href;
                        else {
                            $('#follow_' + type + '_' + type_id).attr('title', 'Follow').html('Follow');
                        }
                    } else if(response == 'added') {
                        $('#follow_' + type + '_' + type_id).attr('title', 'Unfollow').html('Unfollow');
                    } else window.location = response;
                },
                error : function() {}
            });
        }

    }

}(); // App.Favorite

App.auth = function(){
    return {
	authenticated : function(){
	    var auth = false;
	    $.ajax({
		    async: false,
			url: '/admin/authenticated',
			type: 'GET',
			data: '',
			success: function(result) {
                        if(result == 'true') {
			    auth = true;
                        }
		    }
		});
	    return auth;
	}, // authenticated
	authenticate : function(){
	    var auth = App.auth.authenticated();
	    if(auth != true){
		var pwd = prompt('Admin authentication password', '');
		$.ajax({
			async: false,
			    url: '/admin/authenticate',
			    type: 'POST',
			    data: {'pwd': pwd},
			    success: function(result) {
			    if(result == 'true') {
				auth = true;
			    } else {
				alert('Failed to authenticate admin');
			    }
			},
			    error : function(){
			    alert('Connection error');
			}
		    });
	    }
	    return auth;
	}, // authenticate
	become : function(email){
	    if(App.auth.authenticate()){
		App.post('/admin/users/become',
			 [{'type' : 'text', 'name' : 'data[user][email]', 'value' : email}]);
	    } // if
	}
    } // return
}();

// Item functions
App.Item = function(){
    return {
        init : function() {
            var itemTimer = null;
            $('.item').mouseenter(function() {
                // Clear timer
                if(itemTimer != null) clearTimeout(itemTimer);
                // Set hover state
                var item = $(this);
                if($(this).hasClass('hoverable')) $(this).css('background-position', 'left -1080px');
                // Create new timer
                itemTimer = setTimeout(function(){App.Item.open(item);item = null;}, 500);
            });
            $('.item').mouseleave(function() {
                // Clear timer
                clearTimeout(itemTimer);
                // Unset hover state
                if($(this).hasClass('hoverable')) $(this).css('background-position', 'left -80px');
            });
        },
        open : function(item) {
            var inner = item.children('.inner');
            var height = inner.height();
            var options = item.find('.options');
            inner.stop().animate({
                'height': height + options.outerHeight() + 'px'
            }, 150, function() {
                options.fadeIn(100);
                // On leave
                item.mouseleave(function() {
                    options.fadeOut(100, function() {
                        inner.stop().animate({
                            'height': height + 'px'
                        }, 150);
                    });
                });
            });
        }
    }
}();

// Options functions
App.Options = function(){
    return {
        show : function(element){
            var diff = $('#options').outerWidth() - $(element).outerWidth();
            $(element).addClass('active').blur();
            $('#options').removeClass('hidden').css({
                //'left': $(element).position().left - diff + 10 + 'px',
                'right': 0,
                'margin-top': '30px'
            });
        },
        submit : function(element){
            $(element).parents('form').submit();
        },
        close : function() {
            $('#options').addClass('hidden');
            $('a[name=options]').removeClass('active');
        },
        rows : function(amount, element) {
            $('#options #rows a').removeClass('fBold');
            $(element).addClass('fBold').blur();
            $('#options input[name="data[display_rows]"]').val(amount);
        }
    }
}();

// Gallery
App.Gallery = function() {
    return {
        init: function() {
            $('.article:first').show();
            $('.blog:first').show();
            $('.group:first').show();
            $('.user:first').show();
            $('ul.unigallery li img').hover(
                function() {
                    $(this).css('z-index', 100);
                    var toWidth = '124px';
                    var toHeight = '93px';
                    if($(this).parents('.unigallery').hasClass('wide')) {
                        toWidth = '140px';
                        toHeight = '105px';
                    }
                    $(this).stop().animate({
                        marginTop: '-10px',
                        marginLeft: '-10px',
                        width: toWidth,
                        height: toHeight
                    }, 200);
                },
                function() {
                    $(this).css('z-index', 0);
                    var toWidth = '104px';
                    var toHeight = '78px';
                    if($(this).parents('.unigallery').hasClass('wide')) {
                        toWidth = '120px';
                        toHeight = '90px';
                    }
                    $(this).stop().animate({
                        marginTop: '0',
                        marginLeft: '0',
                        width: toWidth,
                        height: toHeight
                    }, 200);
                }
            );
        },
        show: function(id) {
            $('.article').hide();
            $('.blog').hide();
            $('.group').hide();
            $('.user').hide();
            $('#article-' + id).show();
            $('#blog-' + id).show();
            $('#group-' + id).show();
            $('#user-' + id).show();
        },
        expand: function(element) {
            
        }
    }
}();
App.check=function(){
    return{
    url:function(){
    var substr = String($('#url').val()).split('//');
    if (((substr[0]=='http:')&&(substr[1]=='http:'))||((substr[0]=='https:')&&(substr[1]=='http:'))||((substr[0]=='https:')&&(substr[1]=='https:'))||((substr[0]=='http:')&&(substr[1]=='https:'))){
//        url=substr[0].split('//');
        if(substr[2]!=null)
        $('#url').val(substr[1]+'//'+substr[2])
        else $('#url').val(substr[1]+'//');
    }
    }
    }
}();
App.FB=function(){
return{
    meta:function(title,url,img,type){
            var tag=new Array(7)
            for (i=1; i <8; i++)
            tag[i]=new Array(2)
            tag[1][1]="og:title"   
            tag[1][2]=title;
            tag[2][1]="og:url";
            tag[2][2]="http://dev.zingsphere.com"+url;
            tag[3][1]="og:site_name";
            tag[3][2]="Zingsphere";
            tag[4][1]="og:image"
            tag[4][2]=img
            tag[5][1]="og:type";
            tag[5][2]="website";  
            tag[6][1]="og:description";
            tag[6][2]="Zingsphere-rediscover the blogosphere"
            tag[7][1]="fb:app_id";
            tag[7][2]="112152758881502";
        
             for (var i=1;i<8;i++){
            var t = '<meta />';
            var mt = $(t).appendTo('head');
            mt.attr('property', tag[i][1]);
            mt.attr('content', tag[i][2]);             
                                      }
                                      
            tag[1][1]='name';
            tag[1][2]=title;
            tag[2][1]='image';
            tag[2][2]=img;
            tag[3][1]="description"
            tag[3][2]="Zingsphere-rediscover the blogosphere"   
            for (i=1;i<4;i++){
            var t = '<meta />';
            var mt = $(t).appendTo('head');
            mt.attr('name', tag[i][1]);
            mt.attr('content', tag[i][2]);             
                                      }
    }
}

}();
