
//<![CDATA[

/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
// Name changed to CFClass due do naming conflict in prototype
// Documentation: http://ejohn.org/blog/simple-javascript-inheritance/
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.CFClass = function(){};
  
  // Create a new Class that inherits from this class
  CFClass.extend = function(prop) {
    var _super = this.prototype;
    
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
    
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" && 
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
            
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
            
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;
            
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
    
    // The dummy class constructor
    function CFClass() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    
    // Populate our constructed prototype object
    CFClass.prototype = prototype;
    
    // Enforce the constructor to be what we expect
    CFClass.prototype.constructor = CFClass;

    // And make this class extendable
    CFClass.extend = arguments.callee;  
    
    return CFClass;
  };
})();



/**
* @projectDescription CFGlobal contains a bunch of methods needed for the Clipfish.de website
*                     To provider better overview the classes are organized into namespace like objects
*                     These methods are globally available, but sometimes run in the scope of a specific Class instance
*/

var CFGlobal = {};


/****************************************************
* IVW METHODS
*/

CFGlobal.IVW = {
    reload: function() {
        var imgUrl2;
        var _ivw = '';
        var _agof = '';

        var ref = document.referrer;
        var ivwPre = '/clipfish/';
        var ivw2 = $j('#ivw2');
        var urlPre = 'http://clipfish.ivwbox.de/cgi-bin/ivw/CP/';
        if (ivw2) {
            if (arguments.length == 2) {
                // ivw- and agof-code changes
                 _agof = arguments[0];
                 _ivw = arguments[1];
                imgUrl2= urlPre+ _agof + ';' + ivwPre + _ivw + '?r=' + ref + '&d=' + Math.round(1000000 * Math.random());
            } else if (arguments.length == 1 && (typeof _initialAGOF) == 'string') {
                // only new ivw-code, agof-code doesnt change
                 _agof = _initialAGOF;
                 _ivw = arguments[0];
                imgUrl2= urlPre+ _agof + ';' + ivwPre + _ivw + '?r=' + ref + '&d=' + Math.round(1000000 * Math.random());
            } else if (((typeof _initialAGOF) == 'string') && ((typeof _initialIVW) == 'string')) {
                // real reload: use ivw and agof of the page
                imgUrl2= urlPre + _initialAGOF + ';' + ivwPre + _initialIVW + '?r=' + ref + '&d=' + Math.round(1000000 * Math.random());
            } else {
            
                var pos2 = ivw2.attr('src').indexOf('&');
                imgUrl2 = ivw2.attr('src').substring(0, pos) + '&d=' + Math.round(1000000 * Math.random());
                imgUrl2 = imgUrl2.replace(/r=&/, 'r=' + ref + '&');
            }
            ivw2.attr('src', imgUrl2);
        }
   
        var ivwint = $j('#ivwint');
        if(ivwint && typeof _ivw != 'undefined' && _ivw)
        {
            if((_ivw.substring(0,6) == 'videos') && _ivw.substr(_ivw.length -6) == 'senden')
            ivwint.attr('src', 'http://ivw.clipfish.de/cgi-bin/ivw/CP/test.gif;/interne_messung/clipfish/player/versenden' +'?d=' + Math.round(1000000 * Math.random()));

        }
    },

    reloadFromPlayer: function(ivwFunction) {
        var ivwTag;

        if (window._initialIVW) {
            ivwTag = window._initialIVW + '/' + ivwFunction;
        } else {
            // Fallback
            if (window.video && window.video.category_ivw_name) {
                ivwTag = window.video.category_ivw_name + 'player/' + ivwFunction;
            } else {
                ivwTag = 'player/' + ivwFunction;
            }
        }
        try
        {
            _gaq.push(['_trackPageview', '/virtual/' + pageTrackerEvent + '/']);

        }
        catch (e)
        {
            // do nothing, don't show errors...
        }
        CFGlobal.IVW.reload(ivwTag);
    }
};

/****************************************************
* AUTHENTICATION METHODS
* jQuery migration finished
*/

CFGlobal.Auth = {

    observeGlobalElements: function() {
    	$j('#CFNavigationFormLoginSubmit').click(function(event) {
    		CFGlobal.Auth.onSubmit(event);
        });
    },
    
    onSubmit: function(evt) {
   	 var elFrm = $j('#cfloginform');
   	 var url = elFrm.attr('action');
   
   	 var username = elFrm.find('#CFNavigationFormLoginInputUsername').val();
   	 var password = elFrm.find('#CFNavigationFormLoginInputPassword').val();
   	 var data = { username: username, password: password };

     $j.ajax({
         url: url, 
         type: "POST",
         data: data, 
         success: function(data, status){
        	 if (data.status >= 1) {
                 // alles ok, user ist eingeloggt
                 // seite neu laden
                 $j('#cf-login-tooltip').hide();
                 location.href = data.returnpage;
             }
             else {
                 var errortext = "";
                 if (data.errorcode == 10) {
                     errortext = "Beim Login ist ein Fehler aufgetreten. ";
                 }
                 else {
                     errortext = "Beim Login ist ein Fehler aufgetreten. ";
                 }
                 $j('#cf-login-tooltip').show(); 
             }
         },
         dataType: 'json'
     });
   	 
     
        CFGlobal.IVW.reload();
    },
    
    onFacebookLoginResponse: function(response) {
		var url =  $j('#cfloginform').attr('action');
		if(response.accessToken && response.userID) {
			var data = { 
				facebookUserID: response.userID, 
				facebookAccessToken: response.accessToken 
			};
		} else {
			return false;
		}
        $j.ajax({
            url: url, 
            type: "POST",
            data: data, 
            success: function(data, status){
            	if (data.status == 2) {
            		CFGlobal.Site.redirect( location.href, { newfacebookuser : 1 } );
            	} else if (data.status == 1) {
            		CFGlobal.Site.redirect( location.href );
                } else {
                	if(data.errorcode != 1) {
                        errortext = "Beim Login mit deinem Facebook Account ist ein Fehler aufgetreten. ("+data.errorcode+")";
                        $j('#cf-login-tooltip .cf-tooltip-text').html("<p>"+errortext+"</p>");
                        $j('#cf-login-tooltip').show();
                	}
                }
            },
            dataType: 'json'
        });
    }    
    
};

/****************************************************
* EMAIL VALIDATION
*/

CFGlobal.Email = {
    /**
    * NOTE: this method is borrowed from http://www.drweb.de/javascript/email_check.shtml
    *       it already has been used in the old clipfish page. just copied over here...
    * NOTE: as there are domains with umlauts available, added umlaut-checking
    */
    validateEmail: function(s) {
        var a = false;
        var res = false;

        if(typeof(RegExp) == 'function') {
            var b = new RegExp('abc');
            if(b.test('abc') == true){a = true;}
        }

        if(a == true) {
             reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_\\ö\\ä\\ü\\Ö\\Ä\\Ü]+)(\\@)([a-zA-Z0-9\\-\\ö\\ä\\ü\\Ö\\Ä\\Ü]+\\.)+([a-zA-Z]{2,})$');
            
            //   reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_\\ö\\ä\\ü\\Ö\\Ä\\Ü]+)'+ '(\\@)([a-zA-Z0-9\\-\\ö\\ä\\ü\\Ö\\Ä\\Ü\\.]+)'+'(\\.)([a-zA-Z]{2,4})$');
            res = (reg.test(s));
        } else {
            res = (s.search('@') >= 1 && s.lastIndexOf('.') > s.search('@') && s.lastIndexOf('.') >= s.length-5);
        }

        return(res);
    }
};


/****************************************************
* DATE FORMATTERS
*/

CFGlobal.Date = {

    /**
    * @method: formattedDateFromISODate - converts an ISO date string to the form: 'dd.mm.yyyy hh:mm Uhr'
    * @param str - string with format 'yyyy-mm-dd hh:mm:ss'
    */
    formattedDateFromISODate: function(str) {
        if (!str || str == '') return;
        var tmp = str.split(' ');
        var tmpDt = tmp[0].split('-'); // date array
        var tmpTm = tmp[1].split(':'); // time array
        return tmpDt[2] + '.' + tmpDt[1] + '.' + tmpDt[0] + ' ' + tmpTm[0] + ':' + tmpTm[1] + ' Uhr';
    }
};

CFGlobal.Categories = {

    /**
    * @method observerListCategoryChanged - observes first <select> identified by name for change event
    */
    observeListCategoryChanged: function(name) {
        var elms = $j(name);
        if(elms.length > 0) {
            elms.change(function() {
                window.location = $j(this).find('option:selected').val();
            });
        }
    },

  
};


/****************************************************
* COMMENTS RELATED CALLBACKS
*/

CFGlobal.Comments = {

    /**
    * @method onCreateCommentViewsWithData - triggered when new data is successfully loaded in a CFComments instance
    * @param json - json data returned from the server
    * @return nothing.
    *
    * IMPORTANT: this method is executed in the scope of a specific CFComments instance,
    *            so the keyword 'this' refers to the CFComments instance which triggered this method !!!
    */
    onCreateCommentListWithData: function(json) {
        var count = json.result.comments.length;
        var html = null;
        
        // NOTE: onCreatePostWithData calls onCreateReplyWithData directly if the post already contains a reply
        for (var i = 0; i < count; ++i) {
            html = this.onCreatePostWithData(json.result.comments[i], i);
            if (html) {
                this.addItem2(html);
            }
        }

    
    },
   

    /**
    * @method onCreatePostWithData - generates a DOM node from a Json comment object
    * @param json - a Json commment object
    * @param rowStyle - comments row highlighting class
    * @return the created node
    *
    * IMPORTANT: this method is executed in the scope of a specific CFComments instance,
    *            so the keyword 'this' refers to the CFComments instance which triggered this method !!!
    *
    * NOTE: this method creates identical code as the templates do
    */
    onCreatePostWithData: function(json, rowIndex) {
        var rowStyle = (rowIndex % 2 == 0) ? this.config.oddRowClass : this.config.evenRowClass;
        var editable = (user.id != json.commentator_id && this.config.owner && !json.reply);

        
        var html = '<li id="' + this.config.commentItemIdPrefix + '_' + json.id + '" class="cf-comment-item' + ((rowStyle.length > 0) ? ' ' + rowStyle : '') + '">';
        html += '<div class="cf-comment-item-image"><a href="' + page.basepath + 'user/' + 
        json.commentator_nickname + '">';
        
        var image = '';
        if (json.commentator_photo != undefined && json.commentator_photo.length > 0) {
            image += '<img src="' + page.imagebase + json.commentator_photo + '" alt="Foto von ' + json.commentator_nickname +
            '" title="Zum Profil von ' + json.commentator_nickname + '"/>';
           
        } else if (json.commentator_sex == "m") {
            // no image available, use male dummy instead
            image += '<img src="' + page.imagebase + 'v2/user/dummy_male.jpg" alt="Foto von ' + json.commentator_nickname + 
            '" title="Zum Profil von ' + json.commentator_nickname + '"/>';
         
        } else {
            // no image available, use female dummy instead
            image += '<img src="' + page.imagebase + 'v2/user/dummy_female.jpg" alt="Foto von ' + json.commentator_nickname + 
            '" title="Zum Profil von ' + json.commentator_nickname + '"/>';
          
        }
        html += image;

        html += '</a></div>';
        html += '<p class="cf-comment-item-date">' + CFGlobal.Date.formattedDateFromISODate(json.creationtime) + '</p>';

        var nick = '<p class="cf-comment-item-nickname cf-bold"><a href="' + page.basepath + 'user/' + json.commentator_nickname +
        '" title="Zum Profil von ' + json.commentator_nickname + '">' + json.commentator_nickname + '</a></p>';
        html += nick;
        
        var message = '<p class="cf-comment-item-message">' + json.content + '</p>';
        html += message;
        
        html += '<div class="cf-no-float">' +  '\240' + '</div>';

         var replyNode = '';
       if (json.reply) {
            
            var replyNode = this.onCreateReplyWithData(json.reply);
            
            //   html += replyNode; don't insert here!
        } else if (this.config.editable && this.config.owner) {
            html += '<a class="cf-comment-item-reply cf-uppercase">Antworten</a>';
        }
        
        if (json.censorstatus != "1" && (this.config.bigfish || (this.config.editable && this.config.owner) )) {
            
            var deleteLinkNode = '<a class="cf-comment-item-delete cf-uppercase">' + unescape('L%F6schen') + '</a>';
            html += deleteLinkNode;
        }
       
        html += '</li>';
      html += replyNode;
        return html;
      
    },

    /**
    * @method onCreateReplyWithData - generates a DOM node from a Json reply comment object
    * @param json - a Json commment object
    * @return the created node
    *
    * IMPORTANT: this method is executed in the scope of a specific CFComments instance,
    *            so the keyword 'this' refers to the CFComments instance which triggered this method !!!
    *
    * NOTE: this method creates identical code as the templates do
    */
    onCreateReplyWithData: function(json) {
        
        
        var html = '<li class="cf-comment-reply-item" id="' + this.config.commentItemIdPrefix + '_' + json.id + '">';
        html += '<ul>';
        html += '<div class="cf-comment-item-image">';
        html += '<a href="' + page.linkbase + 'user/' + json.commentator_nickname + '/">';
        
        var imageNode = '';
        if (json.commentator_photo != undefined && json.commentator_photo.length > 0) {
            imageNode += '<img src="' + page.imagebase + json.commentator_photo + '" alt="Foto von ' + json.commentator_nickname + 
            '" title="Zum Profil von ' + json.commentator_nickname + '"/>';
        } else if (json.commentator_sex == "m") {
            // no image available, use male dummy instead
            imageNode += '<img src="' + page.imagebase + 'v2/user/dummy_male.jpg" alt="Foto von ' + json.commentator_nickname + 
            '" title="Zum Profil von ' + json.commentator_nickname + '"/>';
        } else {
            // no image available, use female dummy instead
            imageNode += '<img src="' + page.imagebase + 'v2/user/dummy_female.jpg" alt="Foto von ' + json.commentator_nickname + 
            '" title="Zum Profil von ' + json.commentator_nickname + '"/>';
        }
        html += imageNode + '</a></div>';
        
        
        html += '<p class="cf-comment-item-date">' + CFGlobal.Date.formattedDateFromISODate(json.creationtime) + '</p>';

        html += '<p class="cf-comment-item-nickname cf-bold">';
        html += '<a href="' + page.linkbase + 'user/' + json.commentator_nickname + '/" title="Zum Profil von ' + 
        json.commentator_nickname + '">' + json.commentator_nickname + '</a></p>';
        html += '<p class="cf-comment-item-message">' + json.content + '</p>';
        html += '<div class="cf-no-float">' + '\240' + '</div>';
        if (json.censorstatus != "1" && (this.config.bigfish || (this.config.editable && this.config.owner) )) {
           var deleteLink = '<a class="cf-comment-item-delete cf-uppercase">' + unescape('L%F6schen') + '</a>';
           html += deleteLink;
        }
       
        html += '</ul>';
        html += '</li>';
        return html;
    }
    
};



CFGlobal.Popup = {
    openWindowWithUrl: function(url) {
        window.open(url, 'CFPopup', 'width=750,height=500,scrollbars=yes');
    }
};

CFGlobal.Popup = {
    openWindowWithUrlAndSize: function(url,width,height) {
        window.open(url, 'CFPopup', 'width='+width+',height='+height+',scrollbars=yes');
    }
};

CFGlobal.Self = {
		windowLocation: function(url) {			
			window.location.href = url;
		}
};

CFGlobal.setToggleBoxButton = function()
{
    $j( ".cf-toggle-box-button" ).click(function() {
        var boxContent = $j(this).parent().parent().children('.cf-rounded-box-content');
        var toggleVideoInfo = false;
        if ($j(this).parents('#cf-video-info'))
        {
            toggleVideoInfo = true;
        }
        if ($j(this).hasClass('cf-down-arrow'))
        {
            boxContent.show('fast');
            $j(this).removeClass('cf-down-arrow').addClass('cf-up-arrow');
            if (toggleVideoInfo)
            {
                $j('#cf-video-info .full-description').show();
                $j('#cf-video-info .truncated-description').hide();
            }
        }
        else
        {
            boxContent.hide('fast');
            $j(this).removeClass('cf-up-arrow').addClass('cf-down-arrow');
            if (toggleVideoInfo)
            {
                $j('#cf-video-info .full-description').hide();
                $j('#cf-video-info .truncated-description').show();
            }

        }
        var ivwTag;
        if (_initialIVW) {
            ivwTag = _initialIVW + '/box_aufzu';
        } else {
            ivwTag = 'box_aufzu';
        }
        CFGlobal.IVW.reload(ivwTag);
        return false;
    });
};

CFGlobal.Site = {
	redirect: function(url, params) {
	    url = url || window.location.href || '';
	    url = url.match(/\?/) ? url : url + '?';
	    if(params != undefined) {
		    for ( var key in params ) {
		        var regExP = RegExp( '[;&]' + key + '=?[^&;]*', 'g' );
		        url = url.replace( regExP, '');
		        url += ';' + key + '=' + params[key]; 
		    }
	    }
	    // cleanup url 
	    url = url.replace(/[;&]$/, '');
	    url = url.replace(/\?[;&]/, '?'); 
	    url = url.replace(/[;&]{2}/g, ';');
	    window.location.replace( url ); 
	}
};

function adlayerExp_ip() {
    $j('#cf-advertisement').show();
}

function adlayerCol_ip() {
    $j('#cf-advertisement').hide();
}


var doIVW = function (firstIVW, secondIVW) {
    var ivwTag;
    if (window._initialIVW) {
        ivwTag = window._initialIVW + '/' +  firstIVW; // was: '/favorit';
    } else {
        if (window.video && window.video.category_ivw_name) {
            ivwTag = window.video.category_ivw_name + '/' + secondIVW; // was: player/favorit';
        } else {
            ivwTag = secondIVW; // was: 'player/favorit';
        }
    }
    CFGlobal.IVW.reload(ivwTag);
};


/**
 * adVisibility
 * 
 * @param obj element
 * @return string
 */
function adVisibility(elem)
{
	if ($j(elem).length === 0) return '';
	
    var docViewTop = $j(window).scrollTop();
    var docViewBottom = docViewTop + $j(window).height();
    var docViewLeft = $j(window).scrollLeft();
    var docViewRight = docViewLeft + $j(window).width();
    
    var elemTop = 0;
    try { // if element is invisible, an error is occurred
        elemTop = $j(elem).offset().top;
    }
    catch (e) {
        elemTop = 0;
    }
  
    var elemBottom = elemTop + $j(elem).height();
    var elemLeft = 0;
    try {
        elemLeft = $j(elem).offset().left;
    }
    catch (e) {
        elemLeft = 0;
    }
    
    var elemRight = elemLeft + $j(elem).width();
	
    var elemVisibleTop, elemVisibleLeft, elemVisibleBottom, elemVisibleRight;
	
	if (elemTop >= docViewTop) {
		if (elemTop < docViewBottom) {
			elemVisibleTop = elemTop;
		} else {
			elemVisibleTop = false;
		}
	} else { // elemTop < docViewTop
		elemVisibleTop = docViewTop;
	}

	if (elemLeft >= docViewLeft) {
		if (elemLeft < docViewRight) {
			elemVisibleLeft = elemLeft;
		} else {
			elemVisibleLeft = false;
		}
	} else { // elemLeft < docViewLeft
		elemVisibleLeft = docViewLeft;
	}

	if (elemBottom <= docViewBottom) {
		if (elemBottom >= docViewTop) {
			elemVisibleBottom = elemBottom;
		} else { // elemBottom < docViewTop
			elemVisibleBottom = false;
		}
	} else { // elemBottom > docViewBottom
		elemVisibleBottom = docViewBottom;
	}
	
	if (elemRight <= docViewRight) {
		if (elemRight > docViewLeft) {
			elemVisibleRight = elemRight;
		} else { // elemRight < docViewLeft
			elemVisibleRight = false;
		}
	} else { // elemRight > docViewRight
		elemVisibleRight = docViewRight;
	}

	if (elemVisibleTop === false || elemVisibleLeft === false || elemVisibleBottom === false || elemVisibleRight === false) {
		return ';ip_v=0';
	} else {
		var elemVisibility = Math.round((elemVisibleRight-elemVisibleLeft)/$j(elem).width() * (elemVisibleBottom-elemVisibleTop)/$j(elem).height()*100); 
		return ';ip_v=' + (elemVisibility==100 ? '1' : '0');
	}
}

jQuery(document).ready(function(){
    CFGlobal.setToggleBoxButton();
    CFGlobal.Auth.observeGlobalElements();

});
//]]>

