skatic.ajax = {
  'current': '/',
  'referer': null,
  'inProgress': []
  };

$(function(){
  //layout = simple
  if (document.title == '') {
    return false;
  }

  // Keep a mapping of url-to-container for caching purposes.
//	var cache = {
    // If url is '' (no fragment), display this div's content.
//		'': $('#wrapper')
//	};

  // Bind an event to window.onhashchange that, when the history state changes,
  // gets the url from the hash and displays either our cached content or fetches
  // new content to be displayed.
  try {
	  $(window).bind('hashchange', function(e) {

		// Get the hash (fragment) as a string, with any leading # removed. Note that
		// in jQuery 1.4, you should use e.fragment instead of $.param.fragment().
		var url = $.param.fragment();

		if (url != '') {
		  skatic.ajax.loadPage(url);
		} else {
		  skatic.ajax.current = document.location.pathname;

		  $(self.parent.document.getElementById('wrapper')).show();
		}
	  });
  } catch (e) {
	  console.info(e);
  }

  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).trigger('hashchange');
  Mint.save();
	try {
		pageTracker._trackPageview(skatic.url.removeGetParams(skatic.ajax.current));
	} catch (e) {
		//pass
	}
  

  setTimeout(function(){
    $('#wrapper').show();
  }, 1000);

  skatic.ajax.replaceLinksWithAnchors();

  try {
    $("#global_loading").bind('ajaxStart', function(){
      $(this).show();
    }).bind('ajaxStop', function(){
      $(this).hide();
    });
  } catch (e) {
    //pass
  }

  $.ajaxSetup({
    'global': true
  });
});

skatic.ajax.replaceLinksWithAnchors = function() {
  var siteTopDomainLength = siteTopDomain.length;
  var links = document.getElementsByTagName('a');
  for (var i = 0; i < links.length; i++) {
    try {
      var lastChar = links[i].href.charAt(links[i].href.length - 1);
    } catch(e) {
      continue;
    }

    if (lastChar == '#') {
      var indexOfSiteTopDomain = links[i].href.indexOf(siteTopDomain);
      var end = links[i].href.length - 1;// - indexOfSiteTopDomain - siteTopDomainLength;
      links[i].href = '#'+links[i].href.substring(indexOfSiteTopDomain + siteTopDomainLength, end);
    }
  }
};

skatic.ajax.loadPage = function(href) {
  //loading flag is set
  if (skatic.ajax.inProgress.in_array(href)) {
    return false;
  }

  if (typeof href == 'undefined') {
    return false;
  }

  var len = skatic.beforeLoadPage.length;
  if (len > 0) {
    for (var i = 0; i < len; i++) {
      var func = skatic.beforeLoadPage.pop();
      func(href);
    }
  }

  var from = skatic.url.removeGetParams(skatic.ajax.current);

  var hrefWithReferer = skatic.url.changeGetParam(href, 'from', from);

  skatic.menu.main.highlight(href);

  $("#global_loading").show();

  //set loading flag
  skatic.ajax.inProgress.push(href);

  $.ajax({
    'url':hrefWithReferer,
    'type':'GET',
    'success':function(response, statusText){
      //remove loading flag
      if (skatic.ajax.inProgress.indexOf(href) != -1) {
        delete skatic.ajax.inProgress[skatic.ajax.inProgress.indexOf(href)];
        skatic.ajax.inProgress.clean(undefined);
      }

      var result = skatic.ajaxResponse(response, statusText, href, from);

	  if (result.in_array('PAGE_HTML_LOADED')) {
		  skatic.onContentShowRun();
	  }

      $("#global_loading").hide();
    },
    'cache':false,
    'global':true,
    'error':function (XMLHttpRequest, textStatus, errorThrown) {
      //remove loading flag
      if (skatic.ajax.inProgress.indexOf(href) != -1) {
        delete skatic.ajax.inProgress[skatic.ajax.inProgress.indexOf(href)];
        skatic.ajax.inProgress.clean(undefined);
      }
      $("#global_loading").hide();
    }
  });
};

skatic.onContentShowRun = function() {
  function run(execFunc) {
    if (typeof execFunc == 'string') {
      if (execFunc.charAt(execFunc.length - 1) != ')') {
        execFunc += '()';
      }
      eval(execFunc);
    } else {
      execFunc();
    }
  }

  if (skatic.onContentShow.once.length > 0 || skatic.onContentShow.persist.length > 0) {
    for (var i = 0; i < skatic.onContentShow.once.length; i++) {
      run(skatic.onContentShow.once[i]);
      delete skatic.onContentShow.once[i];
    }
    skatic.onContentShow.once.clean(undefined);
    for (var i = 0; i < skatic.onContentShow.persist.length; i++) {
      run(skatic.onContentShow.persist[i]);
    }
  }
};

skatic.redirect = function (url) {
  skatic.ajax.loadPage(url);
  document.location.hash = skatic.url.removeGetParams(url);
};

skatic.ajaxResponse = function (response, statusText, ajaxPageUrl, ajaxPageReferer) {
	$('#global_loading').hide();

	if (typeof response == 'object') {
		var result = skatic.parseJsonResponse(response);
	} else if (response.isJSON()) {
		var result = skatic.parseJsonResponse(JSON.parse(response));
	} else {
		$(self.parent.document.getElementById('wrapper')).html(response).show();
		skatic.ajax.current = skatic.url.changeGetParam(ajaxPageUrl, {'from': null, '_': null, 'call': null, 'locationChanged': null});
		skatic.ajax.referer = ajaxPageReferer;
		Mint.save();
		try {
			pageTracker._trackPageview(skatic.url.removeGetParams(skatic.ajax.current));
		} catch (e) {
			//pass
		}

		var result = ['PAGE_HTML_LOADED'];
	}

	if (result.in_array('PAGE_HTML_LOADED')) {
		//hide edit profile menu
		if ($('#profilemenu').hasClass('opened')) {
			skatic.menu.profile.close();
		}
		//hide login box
		if ($('#loginbox').hasClass('opened')) {
			$('#loginbox').hide();
		}
	}


	return result;
};

skatic.parseJsonResponse = function (json) {
  var result = [];

  if (typeof json.execute != 'undefined' && skatic.allowedToExecute.in_array(json.execute)) {
    if (typeof json.params != 'undefined') {
      var params = json.params;
    } else {
      var params = [];
    }

    skatic.execute('skatic.executeMethods.'+json.execute, params);
	result.push('CALLBACK_EXECUTED');
  }
  if (typeof json.flash != 'undefined') {
    skatic.flash(json.flash);
	result.push('FLASH_SHOWED');
  }
  if (typeof json.invalidate != 'undefined') {
    skatic.invalidateFields(json.invalidate);
	result.push('FIELDS_INVALIDATED');
  }
  if (typeof json.redirect != 'undefined') {
    skatic.redirect(json.redirect);
	result.push('REDIRECTED');
  }

  return result;
};

skatic.execute = function(method, params) {
  if (typeof params[0] == 'undefined') { //not an array
    params = [params];
  }

  params.foreach(function(key, value){
    params[key] = 'JSON.parse(\''+JSON.stringify(value)+'\')';
  });

  var evalString = method+'('+params.join(',')+')';
  if ($.browser.msie) {
    setTimeout(evalString, 100);
  } else {
    eval(evalString);
  }
};

skatic.refreshPage = function(force) {
  var location = skatic.ajax.current;
  if (location != null) {
    skatic.redirect(location);
  } else if(typeof force != 'undefined' && force) {
    document.location.reload(false);
  } else {
    return false;
  }
};

/**
 * @see Message::send()
 */
function parseMessagesLinks() {
  return skatic.ajax.replaceLinksWithAnchors();
}


skatic.parseLinkUrl = function(href) {
  if (href.indexOf('#') == 0) {
      href = href.substr(1);
  } else if(href.indexOf('#') != -1 && href.length != 1) {
      href = href.substr(href.indexOf('#') + 1);
  }

  if(href.indexOf('?') != -1) {
      href = href.substr(0, href.indexOf('?'));
  }

  return href;
};

$('#wrapper').ready(function(){
  try {
    $('#wrapper').hide();
  } catch (e) {
    //pass
  }
});

$.fn.ajaxLoad = function(url) {
  return this.each(function() {
    var self = this;
    $.ajax({
      'type':'GET',
      'url':url,
      'success':function(response) {
        $(self).html(response);
      },
      'dataType':'html',
      'cache':false
    });
  });
};

