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) $('#tabs .right ul').remove();
      
    },
    
    /**
     * 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) {
	    $('#up_votes_'+type_id).html(Number($('#up_votes_'+type_id).html())+1);
      $('#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 != '') {}
        },
        error : function() {}
      });
    },

	  down: function(type, type_id) {
	    $('#down_votes_'+type_id).html(Number($('#down_votes_'+type_id).html())+1);
      $('#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 != '') {}
        },
        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('noshow');
            $('#tabs .right').html('<ul><li style="margin-right: 0;"><a href="javascript:App.tips.show();"  title="Show tips for current section">?</a></li></ul>');
          },
          error : function() {}
        });
	    });
	    // Previous click handler
	    $('#tips .links a[name=prev]').click(function() {
	      var id = $('input[name=tip_id]').val();
	      App.tips.previous(id);
	    });
	    // Next click handler
	    $('#tips .links a[name=next]').click(function() {
	      var id = $('input[name=tip_id]').val();
	      App.tips.next(id);
	    });
	  },
	  
	  show: function() {
	    if($('#tip').length) $('#tip').removeClass('noshow');
	    $('#tabs .right ul').remove();
//      $.ajax({
//        url : '/tips',
//        type : 'POST',
//        data : {'type': 'show'},
//        success : function(response) {
//          if(response != '') {
//            window.location.reload();
//          }
//        },
//        error : function() {}
//      });
    },
    
	  previous: function(id) {
      $.ajax({
        url : '/tips',
        type : 'POST',
        data : {'type': 'prev', 'id': id},
        success : function(response) {
          if(response != '') {
            $('#tips .tip').html(response);
          }
        },
        error : function() {}
      });
    },
    
	  next: function(id) {
      $.ajax({
        url : '/tips',
        type : 'POST',
        data : {'type': 'next', 'id': id},
        success : function(response) {
          if(response != '') {
            $('#tips .tip').html(response);
          }
        },
        error : function() {}
      });
      
    }
    
	}
	
}(); // App.Tips

// Favorite
App.favorite = function() {
  
	return {
		
	  init: function() {
	  },
	  
	  toggle: function(type, type_id) {
      $.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');
          }
        },
        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
}();
