/*
  Closedsitepro plugin
  (P) PSNet, 2008 - 2011
  http://psnet.lookformp3.net/
*/

function in_array (needle, haystack, strict) {
	var found = false, key, strict = !!strict;

	for (key in haystack) {
		if ((strict && haystack [key] === needle) || (!strict && haystack [key] == needle)) {
			found = true;
			break;
		}
	}
	return found;
}

// ---

jQuery (document).ready (function ($) {

  function Closedsitepro_ParseSiteURL (URL) {
    URL = $.trim (URL).replace (Closedsitepro_Host, '');
    // but maybe # need to block, coz js not always allowed (for example - AJAX)
    if ((URL == '') || (URL == '/') || (URL == '/#') || (URL == '#')) return false;
    
    // deleting all left and right slashes
    var regexpLeftS = /^\//;
    var regexpRightS = /\/$/;
    URLWOSlashes = (regexpLeftS.test (URL)) ? URL.substr (1) : URL;
    URLWOSlashes = (regexpRightS.test (URLWOSlashes)) ? URLWOSlashes.substr (0, URLWOSlashes.length - 1) : URLWOSlashes;
    
    // split to array on each /
    URLArray = URLWOSlashes.split ('/');
    
    return URLArray;
  }
  
  // ---

  if (Closedsitepro_UserLogined) return false;
  
  $ ('a[href^="' + Closedsitepro_Host + '"]').each (function () {
    $ (this).bind ('click', function () {
      // parse this url user wish to go
      Closedsitepro_ParsedURL = Closedsitepro_ParseSiteURL (this.href);

      // if this link is index (/) or JS (#) page - go out, nothing to do, allow click
      if (!Closedsitepro_ParsedURL) return true;
    
      AllowClick = false;
      
      // check url with rules
      for (AccessKey in Closedsitepro_AccessRules) {
        CurrentSubRule = Closedsitepro_AccessRules [AccessKey];
        
        // check url. we have 2-level urls in LS
        // check first level
        if (Closedsitepro_ParsedURL [0] == AccessKey) {
          // this is that rule. check up sub url (second level)
          
          // if no subrules - allow all
          if (CurrentSubRule.length == 0) {
            AllowClick = true;
            break;
          }
          
          // if there is subrule and second level - check subrule
          if ((CurrentSubRule.length != 0) && (Closedsitepro_ParsedURL [1])) {
            if (in_array (Closedsitepro_ParsedURL [1], CurrentSubRule)) {
              AllowClick = true;
              break;
            }
          }
          
          // if there is subrule but not second level - disallow (break)
          if ((CurrentSubRule.length != 0) && (!Closedsitepro_ParsedURL [1])) {
            break;
          }
        }
      }
      
      // allow or deny access
      if (!AllowClick) {
        ls.msg.error (Closedsitepro_Msg_Error, Closedsitepro_Msg_Need_Autorization);
        $ ('#login_form_show').trigger ('click');
        return false;
      }
    }); // click
  }); // each
  
});

