/**
 *
 * Perform jQuery library
 * Developed by Perform
 *
 * Built on top of the jQuery library
 * http://jquery.com
 *
 * Description: wrapes basic functionality needed on almost every page
 * Version: 1.0 - isLoggedIn()
 *              - isSubscribed()
 *              - isEventPermitted()
 *              - getUserDetails()
 *              - getCookie()
 *              - setCookie()
 *              - deleteCookie()
 *              - getChip()
 *              - setChip()
 *              - deleteChip()
**/
 var perform = (function(){
   var COOKIE_DELIMITER = '; '; /*semicolon space*/
   var COOKIE_VALUE_DELIMITER = '='; /*equals*/
   var QUERY_STRING_PARAMS_DELIMITER = '&'; /*&amp;*/
   var QUERY_STRING_VALUE_DELIMITER = '=';  /*equals*/
   
   /**
    * getQueryStringDetails
    * get information about specific keyword in query string
    * @param query (string) query string
    * @param key (string) which keyword should be returned
    * @param pairsDeleimiter (string) [OPTIONAL] which string is used as delimiter of pairs
    *                                            by default QUERY_STRING_PARAMS_DELIMITER  constant is used
    * @param keyValueDelimiter (string) [OPTIONAL] which string is used as delimiter of key and valeu
    *                                              by default QUERY_STRING_VALUE_DELIMITER constant is used
    */ 
   function getQueryStringDetails(query, key, pairsDelimiter, keyValueDelimiter){
     if (typeof pairsDelimiter != 'string'){
       pairsDelimiter = QUERY_STRING_PARAMS_DELIMITER;
     }

     if (typeof keyValueDelimiter != 'string'){
       keyValueDelimiter = QUERY_STRING_VALUE_DELIMITER;
     }
     if (key.indexOf(pairsDelimiter)==-1 && key.indexOf(keyValueDelimiter)==-1){ 

       var pairsDelimiterLength = pairsDelimiter.length,
           search_arg = key + keyValueDelimiter,
           search_arg_length = search_arg.length,
           startPos = 0,
           queryLength = query.length;
         
       while (startPos <= queryLength - search_arg_length){
         var endPos = query.indexOf(pairsDelimiter, startPos);
         if (endPos == -1){
           endPos = queryLength; /*no more key/value pairs found*/
         }

         if (query.substring(startPos, startPos+search_arg_length)==search_arg){
           /*we have found holy grail*/
           var details = {
             startPos : startPos,
             endPos : endPos,
             valueStartPos: startPos + search_arg_length,
             value: query.substring(startPos + search_arg_length, endPos)
           }
           return details;
         }  
         startPos = endPos + pairsDelimiterLength;
       }
     }
     return false;
   }

   
   
   return {
     /**
      * perform.isLogedIn
      * Check whether user is logged in or not
      * @return (boolean) true when user is logged in
      * @todo Single Sign On
      */
     isLoggedIn : function(){
       var uicExpireTimeStamp = perform.getChip('UIC','expiryTimestamp');
       var userCookie = perform.getCookie('user');

       if (userCookie !== false || uicExpireTimeStamp !== false){
         if (userCookie === false || uicExpireTimeStamp === false || uicExpireTimeStamp < perform.getCurrentTimeStamp()){
           perform.logout();
         } else {
           return true;
         }
       }
       return false;
     },
     /**
      * perform.isSubscribed
      * Check whether user is subscribed or not
      * @return (boolean) true when user is subscribed
      * @todo Pay Per View functionality
      */
     isSubscribed : function(){
       var userInfo = perform.getUserDetails();
       return (userInfo.subscribed === 'yes');
     },
     /**
      * perform.isEventPermitted
      * Check if event is permitted for the user (xml).
      */
     isEventPermitted : function(eventId, callback){
       if(this.isLoggedIn()) {
         $.ajax({
           type: 'GET',
           dataType: 'xml',
           url: '/decision/global/decisions/eventPermissions/eventId/'+eventId+'',
           success: function(xml) {
             if($(xml).find('event').length == 0) {
               callback(false);
             } else {
               $(xml).find('event').each(function() {
                 if($(this).attr('id') == eventId) {
                   callback($('permitted', this).text());
                 }
               });
             }
           },
           error: function() {
               callback(false);
           }    
         });
       } else {
         callback(false);
       }
     },
     logout: function(){
       var iframe = document.createElement('iframe');
       iframe.onload = function(){location.reload(true)};
       iframe.style.display = "none";
       iframe.src = "https://secure.euroleague.tv/system/userlogout";
       document.body.appendChild(iframe);
     },
     getCurrentTimeStamp: function(){
       var currentDate = new Date();
       return currentDate.getTime();
     },
     /**
      * perform.getUserDetails
      * Get all details from user cookie
      * @return (object) object containing all user details, in time of implementation following details were availiable:
      *                  - username
      *                  - creationdate
      *                  - lastupdatedate
      *                  - localecountrycode
      *                  - localelanguagecode
      *                  - title
      *                  - firstname
      *                  - lastname
      *                  - emailaddress
      *                  - subscribed
      */
     getUserDetails : function(){
       var user = perform.getCookie('user');
       if (user!==false && perform.isLoggedIn()){        
         if (user.charAt(0) === '"' && user.charAt(user.length-1) === '"'){
           user = user.substring(1,user.length-1);
         }

         var parts = user.split(QUERY_STRING_PARAMS_DELIMITER);
         var details = {};
         
         for (var i = 0; i<parts.length; i++){
           var tmp = parts[i].split(QUERY_STRING_VALUE_DELIMITER);
           var key = tmp.shift();
           var value = tmp.join(QUERY_STRING_VALUE_DELIMITER);
           details[key] = value;
         }
         return details;
       }
       return false;
     },
     /**
      * perform.getCookie
      * Get cookie indetified by name
      * @param (string) name name of cookie
      * @param (boolean) OPTION decode whether the cookie should be decoded, by default set to true
      * @return (boolean/string) returns cookie value, if not found false
      */
     getCookie : function(name, decode){
       if (document.cookie && document.cookie!=''){
         if (typeof decode == 'undefined'){
           decode = true;
         }
     
         var details = getQueryStringDetails(document.cookie, name, COOKIE_DELIMITER, COOKIE_VALUE_DELIMITER);
         if (details !== false){
           var cookie = details.value;
           if (decode){
             cookie = decodeURIComponent(cookie);
           }
           return cookie;
         }
       }
       return false;
     },
     /**
      * perform.setCookie
      * Set cookie
      * @param (string) name
      * @param (string) value
      * @param (object) OPTIONAL options, following options are recognized
      *                 (date|number) expires.      If not specified, only session cookie is created
      *                                             If date is provided, this date object is used
      *                                             If integer is provided, it is used as offset in days from current date object
      *                 (string) path.              If not specified path is not specified in cookie
      *                 (string) domain             If not specified domain is not specified in cookie
      *                 (boolean) secure            If specified to true cookie is not mark as secure
      * @param (boolean) OPTIONAL encode If specified to false the value is not encoded before adding to cookie
      */
     setCookie : function(name, value, options, encode){
       if (typeof encode == 'undefined'){
         encode = true;
       }

       var cookie = name + '=' + (encode?encodeURIComponent(value):value);
       options = options || {};
     
       /*Add path setting*/
       if (typeof options.path == 'string'){
         cookie = cookie + '; path=' + options.path;
       }
        
       /*Add expires setting*/
       if (typeof options.expires != 'undefined' && (typeof options.expires == 'number' || typeof options.expires.toUTCString == 'function')){
         var date;
         if (typeof options.expires == 'number'){
           date = new Date();
           date.setTime(date.getTime() + (options.expires * 86400000)); /*24*60*60*1000 - 1 day in miliseconds*/
         } else {
           date = options.expires;
         }
         cookie = cookie + '; expires=' + date.toUTCString();
       }
         
       /*Add domain settings*/
       if (typeof options.domain == 'string'){
         cookie = cookie + '; domain='+options.domain;
       }
      
       /*Add secure settings*/
       if (typeof options.secure != 'undefined' && options.secure == true){
         cookie = cookie + '; secure';
       }

       document.cookie = cookie;
       return true;
     },
     /**
      * perform.deleteCookie
      * deleteCookie
      * @param name (string) name of cookie, which should be deleted
      * @param name (object) options, @see setCookie for more information
      * @return (boolean) true, when cookie was deleted
      */
     deleteCookie: function(name, options){
       options = options || {};
       options.expires = -1;
       return perform.setCookie(name,'',options);
     },
     /**
      * perform.getChip
      * get chip of cookie (possible only when cookie is specified as query string)
      * @param cookieName (string) in which cookie is chip located
      * @param name (string) name of chip
      * @return (boolean|string) false, when cookie or chip was not found, otherwise value of chip
      */
     getChip: function(cookieName, name){
       var cookie = perform.getCookie(cookieName);
       if (cookie !== false){
         var chipDetails = getQueryStringDetails(cookie, name);
         if (chipDetails != false){
           return chipDetails.value;
         }
       }
       return false;
     },
     /**
      * perform.setChip
      * add chip to cookie
      * @param cookieName (string) to which cookie, chip should be added
      * @param name (string) name of chip
      * @param value (string) value that should be assigned to chip
      * @return (boolean) @see perform.setCookie
      * @WARNING - IT IS NOT RECOMENDED TO USE THIS FUNCTION
      *          - AFTER USE, EXPIRATION OF AFFECTED COOKIE IS CHANGED - TILL END OF SESSION
      */
     setChip: function(cookieName, name, value){
       /* firstly delete old chip, so we do not have to care about replacing */
       perform.deleteChip(cookieName, name);
       var cookie = perform.getCookie(cookieName),
           chip = name + '=' + value;
       if (cookie!==false && cookie!=''){
         return perform.setCookie(cookieName,cookie+'&'+chip);
       }else{
         return perform.setCookie(cookieName, chip);
       }
     },
     /**
      * perform.deleteChip
      * delete chip from cookie
      * @param cookieName (string) from which cookie, chip should be removed
      * @param name (string) name of chip, that should be removed
      * @return (boolean) false when chip/cookie was not found, otherwise @see set cookie
      * @WARNING - IT IS NOT RECOMENDED TO USE THIS FUNCTION
      *          - AFTER USE, EXPIRATION OF AFFECTED COOKIE IS CHANGED - TILL END OF SESSION
      */
     deleteChip: function(cookieName, name){
       var cookie = perform.getCookie(cookieName);
       if (cookie !== false){
         var chipDetails = getQueryStringDetails(cookie, name);
         if (chipDetails != false){
           var beforeChip = '';
           var afterChip = '';
           if (chipDetails.startPos != 0){
             beforeChip = cookie.substring(0,chipDetails.startPos-1);
           }
           
           if (chipDetails.endPos < cookie.length){
             afterChip = cookie.substring(chipDetails.endPos+1, cookie.length);
           }
           
           cookie = beforeChip + ((beforeChip!='' && afterChip!='')?'&':'') + afterChip;
           
           return perform.setCookie(cookieName, cookie);
         }
       }
       return true;
     }
   };/*END of return*/
 })();
