String.prototype.getId = function(){return this ? this.replace(/.*_(\d)/,"$1") : 0;}
if( ! document.myhands ) { document.myhands = {};}
 
document.myhands.Api = {
	    //working domain
        domain : 'http://www.myhands.com/',
        auth : 0,
        calltrigger : [],
	cards : 'http://i.myhands.com/files/img/cards/',

        addJavaScriptLib : function (src){
            
                if (document.getElementsByTagName("head")[0].innerHTML.indexOf(src)==-1){
                    var retVal = document.createElement( "script" );
                    retVal.setAttribute( "type", "text/javascript" );
                    retVal.setAttribute( "src", src );
                    document.getElementsByTagName( "head" )[0].appendChild( retVal );
                }
            },

            addCssLib : function (src){
                if (document.getElementsByTagName("head")[0].innerHTML.indexOf(src)==-1){
                    var retVal = document.createElement('link');
                    retVal.setAttribute( "href",src);
                    retVal.setAttribute( "type", "text/css" );
                    retVal.setAttribute("rel","stylesheet");
                    document.getElementsByTagName("head")[0].appendChild(retVal);
                }
           },
	/**
	 * Call api
	 * 
	 * @param {String} method to call
	 * @param {Object} args method arguments 
	 * @param {Boolean} disableCaching do cache disable?
	 * @param {Function} onComplete
	 */
	call : function( method, args, disableCaching, onComplete ) {
            var me=this;
            if (!document.myhands.Api.href){
                document.myhands.Api.href = drisk.Util.parseUri(document.location.href);
            }
            var requestArgs = {};
            // Copy all argumens to request arguments
            for( var i in args ) {
                if (document.myhands.Api.href.queryVars[i]){
                    requestArgs[i] = document.myhands.Api.href.queryVars[i];
                }else {
                    requestArgs[i] = args[i];
                }
            }

            requestArgs.method = method;
            if (!requestArgs.domain){
                if (requestArgs.params){
                    requestArgs.params.domain	= document.myhands.Api.href.domain;
                }
                else {
                    requestArgs.domain	= document.myhands.Api.href.domain;
                }
            }

            if (document.myhands.Api.lang){
                requestArgs['lang']=document.myhands.Api.lang;
            }

            var query=drisk.Util.valueToUrl( requestArgs );

            //checking for dublicate queries
            if (!me.canAjax(query)){
               return false;
            }
            me.canAjax(query,false);
            me.ajaxStart();

            var callQuery=query;
            if( disableCaching ) {
                callQuery +='&rand=' + drisk.Util.randomString( 32 );
            }

            drisk.CrossRPC.call( document.myhands.Api.domain + 'crossrpc.php?' + callQuery, function ( data ){
                    data.homeDomain = 'http://'+document.myhands.Api.href.domain+'/';
                    data.assetsDomain = document.myhands.Api.domain;
                    me.ajaxEnd();
                    me.canAjax(query,true);

                    if (onComplete){
                        onComplete(data);
                    }
                });
                return false;
	},

        ajaxStart : function(){
            if (document.customFields){
                document.customFields.ajaxStart();
            }
        },

        ajaxEnd : function(){
            if (document.customFields){
                document.customFields.ajaxEnd();
            }
        },
        
        canAjax : function (str,val){
            if (document.customFields){
                if (val!=undefined){
                    document.customFields.canAjax(str,val);
                }
                else {
                    return document.customFields.canAjax(str);
                }
            }
            else {
                return true;
            }
        },

        callback : function(){
            if (arguments.length==2){
                var newid=this.calltrigger.length;
                this.calltrigger[newid]=[arguments[0],arguments[1]];
                this.callback(newid);
            }
            else {
                if (eval(this.calltrigger[arguments[0]][0])){
                    this.calltrigger[arguments[0]][1]();
                    this.calltrigger[arguments[0]]=null;
                }
                else {
                    setTimeout("document.myhands.Api.callback("+arguments[0]+");", 100);
                }
            }
        },
    
    
    relocate : function(){
        var query=drisk.Util.valueToUrl( this.href.queryVars );
        document.location.href= this.href.path +(this.href.query?'?':'')+this.href.query+'#'+query;
    },
    init : function(){
        var clientDomain=document.location.href;
                
        //we are in developement
        if (clientDomain.indexOf('myhands.dev')!=-1 || clientDomain.indexOf('&mhdebug=mh6996')!=-1){
            document.myhands.Api.domain = 'http://danas.myhands.dev/';
        }
        //we are in myhands.com
        else if (clientDomain.indexOf('myhands.com')!=-1){
             document.myhands.Api.domain = clientDomain.replace(/(.*myhands.com)\/.*/,'$1/');
        //we are in client external domain
        }else {
            var supported = ['de','ru','fr','nl'];
            var domain=clientDomain.replace(/.*?:\/\/(.*?)?\/.*/,'$1').replace(/:.*/,'').replace(/http:\/\//,'').split('.');
            var newdomain=[];

            //detecting subdomain
            var subdomain = false;
            for (var d=0; d<domain.length;d++){
                for (var i=0; i<supported.length && !subdomain;i++){
                    if (supported[i]==domain[d]){
                        subdomain=domain[d];
                        break;
                    }
                }
                if (domain[d]!='www' && domain[d]!='com' && domain[d]!='myhands' && domain[d]!=subdomain && domain[d]!='forum'){
                    newdomain.push(domain[d]);
                }
            }
            document.myhands.Api.domain = 'http://'+(newdomain.length?newdomain.join('.')+'.':'')+(subdomain?subdomain+'.':'')+'myhands.com/';
        }
        //loading js while loading docsites/all/modules/myhandsserver/js/myhands.js?
        //document.myhands.Api.addJavaScriptLib(document.myhands.Api.domain+'sites/all/modules/myhandsserver/js/myhands.js?vx9');
        document.myhands.Api.addJavaScriptLib(document.myhands.Api.domain+'sites/all/modules/crossrpc/js/crossrpc.js');
        document.myhands.Api.addJavaScriptLib(document.myhands.Api.domain+'sites/all/modules/customfields/customfields.js');
        document.myhands.Api.addCssLib(document.myhands.Api.domain+'sites/all/modules/myhandsserver/myhands.css?v9');
    },
    start : function(){
        if (!window.drisk || !window.drisk.Util || !window.drisk.Util.parseUri){
            setTimeout("document.myhands.Api.start();", 100);
            return;
        }
        //adding missed widgets
        if (document.myhands.witgets && document.myhands.witgets.length){
		for( var i = 0; i < document.myhands.witgets.length; i++ ) {
                    var wgclass=document.myhands.witgets[i].shift();
                    var widget = new document.myhands.widget[wgclass]();
                    widget.construct.apply( widget, document.myhands.witgets[i] );
                    document.myhands.widget.Widget.widgets.push( widget );
		}
        }
        if (this.auth){
            document.myhands.Api.login(document.myhands.widget.Widget.create);
        }
        else {
            document.myhands.widget.Widget.create();
        }

        document.myhands.fixToggle(jQuery(document));
        
        if (document.customFields){
            document.customFields.ajaxDiv=document.customFields.preLoadAjaxDiv;
        }
    },
    url : function (path){
        if (document.myhands.Api.aliases && document.myhands.Api.aliases[path]){
            return document.myhands.Api.aliases[path];
        }else{
            return path;
        }
    },
    authenticate : function(suid,name,token){
        this.auth = Object();
        this.auth.suid=suid;
        this.auth.name=name;
        this.auth.token=token;
    },
    logout : function(){
        document.myhands.Api.call('cross.logout',{},1);
    },
    login : function(after){
        document.myhands.Api.call('cross.auth',{'suid':this.auth.suid,'name':this.auth.name,'token':this.auth.token},1,after);
    }

}
document.myhands.Api.init();

if( !document.myhands.widget ) { document.myhands.widget = {} };
document.myhands.widget.Widget = {

	/** Assets domain */
	assetsDomain : '',
	
	/** Widget pool */
	widgets : [],
	/**
	 * Widget
	 *  
	 * @version $Id$
	 */
	add : function( widgetClass ) {
            var args = [];
            for( var i = 1; i < arguments.length; i++ ) {
                args.push( arguments[i] );
            }
            var widget = new document.myhands.widget[widgetClass]();
            widget.construct.apply( widget, args );
            document.myhands.widget.Widget.widgets.push( widget );
	},

        /**
	 * Create widgets
	 */
	create : function(){
            var Widget = document.myhands.widget.Widget;
            if( Widget.widgets.length > 0 ) {
                var templates = [];
                for( var i = 0; i < Widget.widgets.length; i++ ) {
                    templates = templates.concat( Widget.widgets[i].templates );
                }
                if( templates.length > 0 ) {
                    document.myhands.Api.call( "cross.templates.get", { params : templates }, false, document.myhands.widget.Widget.onTemplatesCallComplete );
                }
            }
	},
	
	/**
	 * Create widgets
	 */
	onTemplatesCallComplete : function( data ) {
		var Widget = document.myhands.widget.Widget;
		// Register templates
		drisk.TemplateManager.addTemplateSources( data );
		// Create all widgets
		for( var i = 0; i < Widget.widgets.length; i++ ) {
			Widget.widgets[i].create();
		}
	},
    
    getTemplate : function (tpl,callback){
       if (drisk.TemplateManager.getTemplate(tpl)){
            callback();
            return;
        }

        document.myhands.Api.call( "cross.templates.get", { 'tpl' : tpl }, false, function(data){
            drisk.TemplateManager.addTemplateSources( data );
            callback();
        });
    },
    
    eventHandChange : function(nid){
        return this.event('HandChange',nid);
    },
    
    event : function (){
        var relocate=false;
        
        //looping over widgets
        for(var i=0; i<this.widgets.length; i++){
            //checking for method support
            switch (arguments[0]){
               case 'HandChange':{
                    switch (this.widgets[i].method){
                        //detecting witgets by type
                        case 'cross.get.comments':
                        case 'nodata':
                        case 'mhapi.hand.getLog':{
                              document.myhands.Api.href.queryVars['nid']=arguments[1];
                              this.widgets[i].methodArgs['nid']=arguments[1];
                              this.widgets[i].create();
                              relocate=true;
                              break;
                         }
                    }
                    break;
              }
              case 'formSubmit':{
                   switch (this.widgets[i]['method']){
                       case 'cross.get.comments':{
                          this.widgets[i].create();
                          break;
                       }
                       case 'mhapi.hand.latestComments':{
                            this.widgets[i].create();
                            break;
                        }
                   }
             }
           }
        }
        if (relocate) {
            document.myhands.Api.relocate();
        }
    }
}

document.myhands.widget.EventWidget = function() {};
document.myhands.widget.EventWidget.prototype = {
    construct : function( elementId, template, method, methodArgs ) {
            this.elementId 	= elementId || "";
            this.templates 	= [];
            this.method 	= method || "";
            this.methodArgs = methodArgs || {};
            
            if (methodArgs.call){
                this.call = methodArgs.call;
                this.methodArgs.call=null;
            }
	},
	create : function() {
            if (this.call){
                 this.call(this);
            }
        }
}

/**
 * Latest list widget
 *  
 * @version $Id$
 */
document.myhands.widget.SimpleWidget = function() {};
document.myhands.widget.SimpleWidget.prototype = {
	/**
	 * Construct widget (init vars, etc)
	 */
         construct : function( elementId, template, method, methodArgs ) {
            this.elementId 	= elementId || "";
            this.templates 	= [template];
            this.method 	= method || "";
            this.methodArgs = methodArgs || {};
	},
	/**
	 * Create widget
	 */
	create : function() {
            if (this.method=='nodata'){
                this.methodArgs.assetsDomain = document.myhands.Api.domain;
                this.methodArgs.homeDomain = 'http://'+document.myhands.Api.href.domain+'/';
                this.methodArgs.domain = document.myhands.Api.href.domain;
                this.onDataCallComplete(this.methodArgs);
            }else {
                document.myhands.Api.call( this.method, this.methodArgs, true, jQuery.delegate( this, this.onDataCallComplete ) );
            }
	},
	/**
	 * On get lists call complete
	 */
	onDataCallComplete : function( data ){
	    this.data=data;
            var debug=drisk.TemplateManager.getTemplate( this.templates[0] ).process( data ) ;
            var el=document.getElementById(this.elementId);

            if (el){
                el=jQuery(el);
            }
            else {
                el=jQuery(this.elementId);
            }
            el.html(debug);
	    if (this.methodArgs['call']){
	       this.methodArgs['call'](this);
	    }
	    else {
		el.find('.focus').bind('click',function(event){this.select();});
		el.addClass('processed');
	    }
	}
}

document.myhands.widget.FormWidget = function() {};
document.myhands.widget.FormWidget.prototype = {
	/**
	 * Construct widget (init vars, etc)
	 */
	construct : function( elementId, template, method, methodArgs ) {

            	
                document.myhands.Api.addJavaScriptLib(document.myhands.Api.domain+'/sites/all/modules/crossrpc/js/flx/flXHR.js');
                document.myhands.Api.addJavaScriptLib(document.myhands.Api.domain+'/sites/all/modules/crossrpc/js/jquery.xhr.js');
                document.myhands.Api.callback('jQuery.xhr',function(){
                    document.myhands.Api.addJavaScriptLib(document.myhands.Api.domain+'/sites/all/modules/crossrpc/js/jquery.flXHRproxy.js');
                    document.myhands.Api.callback('jQuery.flXHRproxy',function(){
                       jQuery.flXHRproxy.registerOptions(document.myhands.Api.domain,{xmlResponseText:false,loadPolicyURL:document.myhands.Api.domain+"crossdomain.xml"});
                    });

                });

                this.elementId 	= elementId || "";
		this.templates 	= [template];
		this.method 	= method || "";
		this.methodArgs = methodArgs || {};
        },
	/**
	 * Create widget
	 */
	create : function() {
            document.myhands.Api.call( this.method, this.methodArgs, true, jQuery.delegate( this, this.onDataCallComplete ) );
	},
	/**
	 * On get lists call complete
	 */
	onDataCallComplete : function( data ) {

        jformEl = jQuery("#"+this.elementId);
        jformEl.html( drisk.TemplateManager.getTemplate( this.templates[0] ).process( data ) );
        document.myhands.fixToggle(jformEl);
      
        this.fixTextArea(jformEl);

        var me = this;
	me.data=data;

	if (me.methodArgs['call']){
	    me.methodArgs['call'](me);
	}
	
        jformEl.find('form').each(function(id,el){
            var action=data.assetsDomain+'crossrpc.php?method=cross.form.submit&type=json&domain='+document.myhands.Api.href.domain;
            jQuery(el).find("input[name=op]").bind('click',function(event){
                //checking for dublicate queries
                if (!document.myhands.Api.canAjax('cross.form.submit')){
                    return false;
                }
                document.myhands.Api.canAjax('cross.form.submit',false);
                document.myhands.Api.ajaxStart();

                var zz=jQuery(el).serialize();
                jQuery.ajaxSetup({transport:'flXHRproxy',error:handleError});

                jQuery.post(
                            action,
                            zz,
                            function (data){

                                document.myhands.Api.ajaxEnd();
                                document.myhands.Api.canAjax('cross.form.submit',true);

				//this is opera bug
                                if (data.responseText && (!data['status'] || !data['status'])){
                                   eval('data = '+data.responseText);
                                }
                                if (me.methodArgs['call']){
                                   me.methodArgs['call'](data);
                                }
                                else if (data['error']){
                                    alert(data['error']);
                                }
                                else if (data['status']=='OK') {
                                    if (data['redirect']){
                                        document.location.href='/'+document.myhands.Api.url('poker-hands/all/hand')+'?lid='+data['lid']+'&nid='+data['nid']+'&new=1';
                                    }else {
                                        document.myhands.widget.Widget.event('formSubmit',jformEl.find('input[name=form_id]').val());
                                    }
                                }
			},
                        "json"
                );
                return false;
            });
        });
    },

    fixTextArea : function(html){
        try{
            if (Drupal && !Drupal.behaviors){
                Drupal.behaviors={};
            }
            document.myhands.Api.addJavaScriptLib(document.myhands.Api.domain+'misc/textarea.js');
            document.myhands.Api.callback('Drupal.behaviors.textarea',function(){
                Drupal.behaviors.textarea(html);
            });
        }
        catch(ex){}

    }
}

function handleError(XHRobj,errtype,errObj) {
	alert("Error: "+errObj.number
		+"\nType: "+errObj.name
		+"\nDescription: "+errObj.description
		+"\nSource Object Id: "+errObj.srcElement.instanceId
	);
}


document.myhands.widget.ListWidget = function() {};
document.myhands.widget.ListWidget.prototype = {
	/**
	 * Construct widget (init vars, etc)
	 */
	construct : function( elementId, template, method, methodArgs ) {
		this.elementId 	= elementId || "";
		this.templates 	= [template];
		this.method 	= method || "";
		this.methodArgs = methodArgs || {};
	},
	
	/**
	 * Create widget
	 */
	create : function() {
        document.myhands.Api.call( this.method, this.methodArgs, true, jQuery.delegate( this, this.onDataCallComplete ) );
	},
	/**
	 * On get lists call complete
	 */
	onDataCallComplete : function( data ) {
        var html = drisk.TemplateManager.getTemplate( this.templates[0] ).process( data ) ;
        jQuery("#"+this.elementId).html(html);

        var me=this;
        document.myhands.fixPager(jQuery("#"+this.elementId ), me);
        this.managerButton(jQuery("#"+this.elementId));

        //finding event rows
        jQuery(".handsList").find('.event').each(function(id,el){
			//changing URL for user
			$(this).find('.user a').each(function(){
				$(this).attr('href', $(this).attr('href').replace('poker-hands', 'user'));
			});
            //binding on expanding class clicking
            jQuery(el).find('.ex').bind('click', function(){
                //getting hands table
                var jwg=jQuery('#evn_'+el.id.getId()+'_hands');
                //if table found just show/hide it
                if (jwg.length){
                    if (jwg.css('display')=='none'){
                            jwg.css('display','');
                            jQuery('#list_'+el.id.getId()).attr('src','http://i.myhands.com/files/img/arrowUp.gif');
                        }
                        else{
                            jwg.css('display','none');
                            jQuery('#list_'+el.id.getId()).attr('src','http://i.myhands.com/files/img/arrowDown.gif');
                        }
                }else {
                  var listid=el.id.getId();
                  
                  if (!me.listWg){ me.listWg ={}};
                  me.listWg[listid] = Array();
                  
                  me.listWg[listid].element 	= jQuery(jQuery('#evn_'+listid));
                  me.listWg[listid].template 	= 'mhListHands';
                  me.listWg[listid].method 	= 'mhapi.hand.handsList'
                  me.listWg[listid].methodArgs = {'id':listid };

                  //downloading hands list
                  document.myhands.Api.call( me.listWg[listid].method, me.listWg[listid].methodArgs , true,
                        function(data){
                                //we got data now getting template
                                document.myhands.widget.Widget.getTemplate(me.listWg[listid].template, function(){
                                    var html = drisk.TemplateManager.getTemplate(me.listWg[listid].template).process(data);
                                    //appending data to template
                                    
                                    me.listWg[listid].element.after('<tr id="evn_'+listid+'_hands"><td colspan="10">'+html+'</td></tr>');
                                    
                                    jlist=jQuery('#evn_'+listid+'_hands');

                                    document.myhands.fixPager(jlist.find('.hands'), me.listWg[listid]);
                                    document.myhands.bindMouseMOve(jlist);
                                    jQuery('#list_'+listid).attr('src','http://i.myhands.com/files/img/arrowUp.gif');
                            });
                        });
                }
                return false;
            });
        });
	},

    managerButton : function(jlist){
        jme=this;
        jlist.find('input[type=button]').bind('click',function(event){
            var action=jQuery('#handsManager').val();
                if (action && confirm(jQuery('#areyousure').text())){
                    var request={'lid':Array(),'hid':Array()};
                    jlist.find('input:checked').each(function(id,el){
                        request['lid'].push(el.value);
                    });
                    //console.dir(request);
                    if (request['lid'].length){
                        document.myhands.Api.call( 'mhapi.hand.manager', {'action':action,'data':request}, true,function(data){
                            if (data.action=='refresh'){
                                jme.create();
                            }
                        });
                    }
            }
        });
    }
}


document.myhands.widget.SearchWidget = function() {};
document.myhands.widget.SearchWidget.prototype = {
	construct : function( elementId, template, method, methodArgs ) {
		this.elementId 	= elementId || "";
		this.templates 	= ['mhHandsSearch','mhListHands'];
		this.method 	= method || "";
		this.methodArgs = methodArgs || {};
	},
	create : function() {document.myhands.Api.call( this.method, this.methodArgs, true, jQuery.delegate( this, this.onDataCallComplete ) );},
	onDataCallComplete : function( data ) {
        var me=this;
        jQuery( "#" + this.elementId ).html( drisk.TemplateManager.getTemplate( this.templates[0] ).process( data ) );

	//removing imputs adding imagest
        jQuery("#search-form").find('input.card').each(function(id,el){
            jQuery(el).css('display','none');
            jQuery(el).after('<img class="card" alt="'+el.name+'" src="'+document.myhands.Api.cards+(el.value?el.value:'em')+'.gif">');
        });

        document.myhands.fixCollapse(jQuery("#search-form"));
        //binding images
        jQuery("#search-form").find('img.card').each(function(id,imgel){
                jQuery(imgel).bind('click',function(event){
                    //hiding used icons
                    document.myhands.selectedCard = jQuery(imgel).attr('alt');
                    jQuery('#handsCardsDiv').find('img').css('display','inline');
                    jQuery('#search-form').find('input.card').each(function(id,el){
                        if (el.value!='' && el.value.indexOf('x')==-1){
                            jQuery('#handsCardsDiv').find('img[alt='+el.value+']').css('display','none');
                        }
                    });
                    document.customFields.moveToMouse(event,'handsCardsDiv');
                    jQuery('#handsCardsDiv').css('display','block');
                });
         });
        jQuery('#handsCardsDiv').find('img').bind('click',function(event){
            var selectedVal=jQuery(this).attr('alt');
            jQuery("#search-form").find('input[name='+document.myhands.selectedCard+']').attr('value',(selectedVal=='em'?'':selectedVal));
            jQuery("#search-form").find('img[alt='+document.myhands.selectedCard+']').attr('src',document.myhands.Api.cards+selectedVal+'.gif');
            jQuery("#handsCardsDiv").css('display','none');
            jQuery("#search-form").unbind('click');
        });

        jQuery('#search-form').find('input[name=search]').bind('click',function(event){
            var search= Array();
            jQuery('#search-form').find('input').each(function(id,el){
                if (el.value!='' && el.type=='text'){
                    search[el.name]=el.value;
                }else if(el.type=='checkbox' && el.checked){
                    search[el.name]=1;
                }
            });

            jQuery('#search-form').find('select').each(function(id,el){
                search[el.name]=jQuery(el).val();
            });

            //defining child semi widget params
            me.listWg = Array();
            me.listWg.element 	= jQuery('#searchResult');
            me.listWg.template 	= 'mhListHands';
            me.listWg.method 	= 'mhapi.hand.search'
            me.listWg.methodArgs = search;

            document.myhands.Api.call(me.listWg.method , search, true,
                        function(data){
                                //we got data now getting template
                                document.myhands.widget.Widget.getTemplate(me.listWg.template, function(){
                                   var html = drisk.TemplateManager.getTemplate(me.listWg.template).process(data);
                                    //appending data to template
                                    if (html){
                                        me.listWg.element.html(html);
                                        document.myhands.fixPager(me.listWg.element.find('.hands'), me.listWg);
                                        document.myhands.bindMouseMOve(me.listWg.element);
                                    }
                            });
                        });
        });

        //fixing on submit
        jQuery('#search-form').bind('submit',function(event){
            jQuery('#search-form').find('input[name=search]').trigger('click'); return false;
        });

        if (data.hands){
            var html = drisk.TemplateManager.getTemplate('mhListHands').process(data);
            jQuery('#searchResult').html(html);
            document.myhands.fixPager(jQuery('#searchResult').find('.hands'), me);
            document.myhands.bindMouseMOve(jQuery('#searchResult'));
        }

        jQuery('#search-form').find('input[name=clear]').bind('click',function(event){
            jQuery('#search-form').find('input[type=text]').each(function(id,el){el.value='';});
            jQuery('#search-form').find('img').attr('src',document.myhands.Api.cards+'em.gif');
            jQuery('#search-form').find('select').attr('selectedIndex',0);
            jQuery('#search-form').find('input[type=checkbox]').attr('checked',false);
         });
	}
}

document.myhands.fixToggle=function(jel){
    jel.find('.toggleH2').remove('.processed').each(function(id,el){
        jQuery(el).find('h2').bind('click',function(event){
            var wr=jQuery(el).find('.toggleWr');
            if (wr.is('.hidden')){
                wr.removeClass('hidden');
            }
            else {
                wr.addClass('hidden');
            }
        });
        jQuery(el).addClass('processed');
    });
   return false;
}

document.myhands.toggle=function(id){
        if (jQuery(id).is('.hidden')){
            jQuery(id).removeClass('hidden');
        }
        else {
            jQuery(id).addClass('hidden');
        }
        return false;
}

document.myhands.fixCollapse=function(jel){
    jel.find('.collapsible').find('legend').bind('click',function(event){
        if (!jQuery(this).parent().is('.collapsed')){
            jQuery(this).parent().addClass('collapsed');
        }
        else {
            jQuery(this).parent().removeClass('collapsed');
        }
    })
}

document.myhands.fixPager=function (jel,widget){
    
    jel.find('ul.pager').find('a').each(function(id,el){
        var page = drisk.Util.parseUri(el.href).queryVars.page;
        if (!page){page=0;}
        jQuery(el).attr('href','#page='+page);
        jQuery(el).bind('click',function () {
            widget.methodArgs.page=page;
            widget.create();
        });
    });

    jel.find('a.showmore').each(function(id,el){

        var href = drisk.Util.parseUri( el.href ).queryVars;
        document.myhands.Api.href.queryVars.more = href.more;
        jQuery(el).attr('href','#'+drisk.Util.valueToUrl( document.myhands.Api.href.queryVars ) );

        jQuery(el).bind('click',function (event) {
            widget.methodArgs.have = jel.find('tr.hand').length;
            widget.methodArgs.more = href.more;
            document.myhands.Api.call( widget.method, widget.methodArgs, true,
                        function(data){
                                jQuery(el).parent().remove();
                                //we got data now getting template
                                document.myhands.widget.Widget.getTemplate(widget.template, function(){
                                    var html = drisk.TemplateManager.getTemplate(widget.template).process(data);
                                    //appending data to template
                                    jel.append(html);
                                    document.myhands.bindMouseMOve(jel);
                                    document.myhands.fixPager(jel,widget);
                            });
                        });
                });
    });
}

document.myhands.bindMouseMOve = function (jid){
     //now binding on mouse move

    jQuery('.infoOver').removeClass('infoOver');

    jid.find('.hand').each(function(id,el){
        var infoDiv=jQuery('#hand_'+el.id.getId()+'_info');
        jQuery(el).bind('mouseover',function(event){
             document.customFields.moveToMouse(event,infoDiv[0]);
             infoDiv.addClass('infoOver');
        });
        jQuery(el).bind('mouseout',function(){infoDiv.removeClass('infoOver');});
        jQuery(el).bind('mousemove',function(event){
             document.customFields.moveToMouse(event,infoDiv[0]);
        });
    });
}


// On document ready - create all widgets
jQuery(document).ready( function() {
    //jQuery.noConflict();
    document.myhands.Api.start();
    //var code='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" align="middle" style="width: 100%; height: 450px;"codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"" id="handplayerP9UUJWqafegecbc7"><param name="movie" value="http://danas.myhands.dev/handplayer/v2/preloader.swf" /><param name="menu" value="false" /><param name="scale" value="noscale" /><param name="quality" value="high" /><param name="wmode" value="window" /><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="flashvars" value="config=danas.myhands.dev&handId=$1&listId=0&searchId=0"><embed swLiveConnect="true" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" style="width: 100%; height: 450px;" src="http://danas.myhands.dev/handplayer/v2/preloader.swf" name="handplayerP9UUJWqafegecbc7" id="handplayerP9UUJWqafegecbc7" menu="false" scale="noscale" quality="high" wmode="window" allowFullScreen="true" allowScriptAccess="always" flashvars="config=danas.myhands.dev&handId=$1&listId=0&searchId=0" /></object>';
    //document.body.innerHTML = document.body.innerHTML.replace(/\[hand\](.*?)\[\/hand\]/ig, code);
});

/**
 * JQuery delegate plugin
 * 
 * @version $Id$
 */
(function(jQuery) {

/**
 * Function delegate utility
 */
jQuery.delegate = function( object, method ) {
	return function() {
		return method.apply( object, arguments );
	};
};
})(jQuery);


/**
 * TrimPath Template. Release 1.0.38.
 * Copyright (C) 2004, 2005 Metaha.
 * 
 * TrimPath Template is licensed under the GNU General Public License
 * and the Apache License, Version 2.0, as follows:
 *
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the 
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var TrimPath;

// TODO: Debugging mode vs stop-on-error mode - runtime flag.
// TODO: Handle || (or) characters and backslashes.
// TODO: Add more modifiers.

(function() {               // Using a closure to keep global namespace clean.
    if (TrimPath == null)
        TrimPath = new Object();
    if (TrimPath.evalEx == null)
        TrimPath.evalEx = function(src) { return eval(src); };

    var UNDEFINED;
    if (Array.prototype.pop == null)  // IE 5.x fix from Igor Poteryaev.
        Array.prototype.pop = function() {
            if (this.length === 0) {return UNDEFINED;}
            return this[--this.length];
        };
    if (Array.prototype.push == null) // IE 5.x fix from Igor Poteryaev.
        Array.prototype.push = function() {
            for (var i = 0; i < arguments.length; ++i) {this[this.length] = arguments[i];}
            return this.length;
        };

    TrimPath.parseTemplate = function(tmplContent, optTmplName, optEtc) {
        if (optEtc == null)
            optEtc = TrimPath.parseTemplate_etc;
        var funcSrc = parse(tmplContent, optTmplName, optEtc);
        var func = TrimPath.evalEx(funcSrc, optTmplName, 1);
        if (func != null)
            return new optEtc.Template(optTmplName, tmplContent, funcSrc, func, optEtc);
        return null;
    }
    
    try {
        String.prototype.process = function(context, optFlags) {
            var template = TrimPath.parseTemplate(this, null);
            if (template != null)
                return template.process(context, optFlags);
            return this;
        }
    } catch (e) { // Swallow exception, such as when String.prototype is sealed.
    }
    
    TrimPath.parseTemplate_etc = {};            // Exposed for extensibility.
    TrimPath.parseTemplate_etc.statementTag = "forelse|for|if|elseif|else|var|macro";
    TrimPath.parseTemplate_etc.statementDef = { // Lookup table for statement tags.
        "if"     : { delta:  1, prefix: "if (", suffix: ") {", paramMin: 1 },
        "else"   : { delta:  0, prefix: "} else {" },
        "elseif" : { delta:  0, prefix: "} else if (", suffix: ") {", paramDefault: "true" },
        "/if"    : { delta: -1, prefix: "}" },
        "for"    : { delta:  1, paramMin: 3, 
                     prefixFunc : function(stmtParts, state, tmplName, etc) {
                        if (stmtParts[2] != "in")
                            throw new etc.ParseError(tmplName, state.line, "bad for loop statement: " + stmtParts.join(' '));
                        var iterVar = stmtParts[1];
                        var listVar = "__LIST__" + iterVar;
                        return [ "var ", listVar, " = ", stmtParts[3], ";",
                             // Fix from Ross Shaull for hash looping, make sure that we have an array of loop lengths to treat like a stack.
                             "var __LENGTH_STACK__;",
                             "if (typeof(__LENGTH_STACK__) == 'undefined' || !__LENGTH_STACK__.length) __LENGTH_STACK__ = new Array();", 
                             "__LENGTH_STACK__[__LENGTH_STACK__.length] = 0;", // Push a new for-loop onto the stack of loop lengths.
                             "if ((", listVar, ") != null) { ",
                             "var ", iterVar, "_ct = 0;",       // iterVar_ct variable, added by B. Bittman     
                             "for (var ", iterVar, "_index in ", listVar, ") { ",
                             iterVar, "_ct++;",
                             "if (typeof(", listVar, "[", iterVar, "_index]) == 'function') {continue;}", // IE 5.x fix from Igor Poteryaev.
                             "__LENGTH_STACK__[__LENGTH_STACK__.length - 1]++;",
                             "var ", iterVar, " = ", listVar, "[", iterVar, "_index];" ].join("");
                     } },
        "forelse" : { delta:  0, prefix: "} } if (__LENGTH_STACK__[__LENGTH_STACK__.length - 1] == 0) { if (", suffix: ") {", paramDefault: "true" },
        "/for"    : { delta: -1, prefix: "} }; delete __LENGTH_STACK__[__LENGTH_STACK__.length - 1];" }, // Remove the just-finished for-loop from the stack of loop lengths.
        "var"     : { delta:  0, prefix: "var ", suffix: ";" },
        "macro"   : { delta:  1, 
                      prefixFunc : function(stmtParts, state, tmplName, etc) {
                          var macroName = stmtParts[1].split('(')[0];
                          return [ "var ", macroName, " = function", 
                                   stmtParts.slice(1).join(' ').substring(macroName.length),
                                   "{ var _OUT_arr = []; var _OUT = { write: function(m) { if (m) _OUT_arr.push(m); } }; " ].join('');
                     } }, 
        "/macro"  : { delta: -1, prefix: " return _OUT_arr.join(''); };" }
    }
    TrimPath.parseTemplate_etc.modifierDef = {
        "eat"        : function(v)    { return ""; },
        "escape"     : function(s)    { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); },
        "capitalize" : function(s)    { return String(s).toUpperCase(); },
        "default"    : function(s, d) { return s != null ? s : d; }
    }
    TrimPath.parseTemplate_etc.modifierDef.h = TrimPath.parseTemplate_etc.modifierDef.escape;

    TrimPath.parseTemplate_etc.Template = function(tmplName, tmplContent, funcSrc, func, etc) {
        this.process = function(context, flags) {
            if (context == null)
                context = {};
            if (context._MODIFIERS == null)
                context._MODIFIERS = {};
            if (context.defined == null)
                context.defined = function(str) { return (context[str] != undefined); };
            for (var k in etc.modifierDef) {
                if (context._MODIFIERS[k] == null)
                    context._MODIFIERS[k] = etc.modifierDef[k];
            }
            if (flags == null)
                flags = {};
            var resultArr = [];
            var resultOut = { write: function(m) { resultArr.push(m); } };
            try {
                func(resultOut, context, flags);
            } catch (e) {
                if (flags.throwExceptions == true)
                    throw e;
                var result = new String(resultArr.join("") + "[ERROR: " + e.toString() + (e.message ? '; ' + e.message : '') + "]");
                result["exception"] = e;
                return result;
            }
            return resultArr.join("");
        }
        this.name       = tmplName;
        this.source     = tmplContent; 
        this.sourceFunc = funcSrc;
        this.toString   = function() { return "TrimPath.Template [" + tmplName + "]"; }
    }
    TrimPath.parseTemplate_etc.ParseError = function(name, line, message) {
        this.name    = name;
        this.line    = line;
        this.message = message;
    }
    TrimPath.parseTemplate_etc.ParseError.prototype.toString = function() { 
        return ("TrimPath template ParseError in " + this.name + ": line " + this.line + ", " + this.message);
    }
    
    var parse = function(body, tmplName, etc) {
        body = cleanWhiteSpace(body);
        var funcText = [ "var TrimPath_Template_TEMP = function(_OUT, _CONTEXT, _FLAGS) { with (_CONTEXT) {" ];
        var state    = { stack: [], line: 1 };                              // TODO: Fix line number counting.
        var endStmtPrev = -1;
        while (endStmtPrev + 1 < body.length) {
            var begStmt = endStmtPrev;
            // Scan until we find some statement markup.
            begStmt = body.indexOf("{", begStmt + 1);
            while (begStmt >= 0) {
                var endStmt = body.indexOf('}', begStmt + 1);
                var stmt = body.substring(begStmt, endStmt);
                var blockrx = stmt.match(/^\{(cdata|minify|eval)/); // From B. Bittman, minify/eval/cdata implementation.
                if (blockrx) {
                    var blockType = blockrx[1]; 
                    var blockMarkerBeg = begStmt + blockType.length + 1;
                    var blockMarkerEnd = body.indexOf('}', blockMarkerBeg);
                    if (blockMarkerEnd >= 0) {
                        var blockMarker;
                        if( blockMarkerEnd - blockMarkerBeg <= 0 ) {
                            blockMarker = "{/" + blockType + "}";
                        } else {
                            blockMarker = body.substring(blockMarkerBeg + 1, blockMarkerEnd);
                        }                        
                        
                        var blockEnd = body.indexOf(blockMarker, blockMarkerEnd + 1);
                        if (blockEnd >= 0) {                            
                            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
                            
                            var blockText = body.substring(blockMarkerEnd + 1, blockEnd);
                            if (blockType == 'cdata') {
                                emitText(blockText, funcText);
                            } else if (blockType == 'minify') {
                                emitText(scrubWhiteSpace(blockText), funcText);
                            } else if (blockType == 'eval') {
                                if (blockText != null && blockText.length > 0) // From B. Bittman, eval should not execute until process().
                                    funcText.push('_OUT.write( (function() { ' + blockText + ' })() );');
                            }
                            begStmt = endStmtPrev = blockEnd + blockMarker.length - 1;
                        }
                    }                        
                } else if (body.charAt(begStmt - 1) != '$' &&               // Not an expression or backslashed,
                           body.charAt(begStmt - 1) != '\\') {              // so check if it is a statement tag.
                    var offset = (body.charAt(begStmt + 1) == '/' ? 2 : 1); // Close tags offset of 2 skips '/'.
                                                                            // 10 is larger than maximum statement tag length.
                    if (body.substring(begStmt + offset, begStmt + 10 + offset).search(TrimPath.parseTemplate_etc.statementTag) == 0) 
                        break;                                              // Found a match.
                }
                begStmt = body.indexOf("{", begStmt + 1);
            }
            if (begStmt < 0)                              // In "a{for}c", begStmt will be 1.
                break;
            var endStmt = body.indexOf("}", begStmt + 1); // In "a{for}c", endStmt will be 5.
            if (endStmt < 0)
                break;
            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
            emitStatement(body.substring(begStmt, endStmt + 1), state, funcText, tmplName, etc);
            endStmtPrev = endStmt;
        }
        emitSectionText(body.substring(endStmtPrev + 1), funcText);
        if (state.stack.length != 0)
            throw new etc.ParseError(tmplName, state.line, "unclosed, unmatched statement(s): " + state.stack.join(","));
        funcText.push("}}; TrimPath_Template_TEMP");
        return funcText.join("");
    }
    
    var emitStatement = function(stmtStr, state, funcText, tmplName, etc) {
        var parts = stmtStr.slice(1, -1).split(' ');
        var stmt = etc.statementDef[parts[0]]; // Here, parts[0] == for/if/else/...
        if (stmt == null) {                    // Not a real statement.
            emitSectionText(stmtStr, funcText);
            return;
        }
        if (stmt.delta < 0) {
            if (state.stack.length <= 0)
                throw new etc.ParseError(tmplName, state.line, "close tag does not match any previous statement: " + stmtStr);
            state.stack.pop();
        } 
        if (stmt.delta > 0)
            state.stack.push(stmtStr);

        if (stmt.paramMin != null &&
            stmt.paramMin >= parts.length)
            throw new etc.ParseError(tmplName, state.line, "statement needs more parameters: " + stmtStr);
        if (stmt.prefixFunc != null)
            funcText.push(stmt.prefixFunc(parts, state, tmplName, etc));
        else 
            funcText.push(stmt.prefix);
        if (stmt.suffix != null) {
            if (parts.length <= 1) {
                if (stmt.paramDefault != null)
                    funcText.push(stmt.paramDefault);
            } else {
                for (var i = 1; i < parts.length; i++) {
                    if (i > 1)
                        funcText.push(' ');
                    funcText.push(parts[i]);
                }
            }
            funcText.push(stmt.suffix);
        }
    }

    var emitSectionText = function(text, funcText) {
        if (text.length <= 0)
            return;
        var nlPrefix = 0;               // Index to first non-newline in prefix.
        var nlSuffix = text.length - 1; // Index to first non-space/tab in suffix.
        while (nlPrefix < text.length && (text.charAt(nlPrefix) == '\n'))
            nlPrefix++;
        while (nlSuffix >= 0 && (text.charAt(nlSuffix) == ' ' || text.charAt(nlSuffix) == '\t'))
            nlSuffix--;
        if (nlSuffix < nlPrefix)
            nlSuffix = nlPrefix;
        if (nlPrefix > 0) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(0, nlPrefix).replace('\n', '\\n'); // A macro IE fix from BJessen.
            if (s.charAt(s.length - 1) == '\n')
            	s = s.substring(0, s.length - 1);
            funcText.push(s);
            funcText.push('");');
        }
        var lines = text.substring(nlPrefix, nlSuffix + 1).split('\n');
        for (var i = 0; i < lines.length; i++) {
            emitSectionTextLine(lines[i], funcText);
            if (i < lines.length - 1)
                funcText.push('_OUT.write("\\n");\n');
        }
        if (nlSuffix + 1 < text.length) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(nlSuffix + 1).replace('\n', '\\n');
            if (s.charAt(s.length - 1) == '\n')
            	s = s.substring(0, s.length - 1);
            funcText.push(s);
            funcText.push('");');
        }
    }
    
    var emitSectionTextLine = function(line, funcText) {
        var endMarkPrev = '}';
        var endExprPrev = -1;
        while (endExprPrev + endMarkPrev.length < line.length) {
            var begMark = "${", endMark = "}";
            var begExpr = line.indexOf(begMark, endExprPrev + endMarkPrev.length); // In "a${b}c", begExpr == 1
            if (begExpr < 0)
                break;
            if (line.charAt(begExpr + 2) == '%') {
                begMark = "${%";
                endMark = "%}";
            }
            var endExpr = line.indexOf(endMark, begExpr + begMark.length);         // In "a${b}c", endExpr == 4;
            if (endExpr < 0)
                break;
            emitText(line.substring(endExprPrev + endMarkPrev.length, begExpr), funcText);                
            // Example: exprs == 'firstName|default:"John Doe"|capitalize'.split('|')
            var exprArr = line.substring(begExpr + begMark.length, endExpr).replace(/\|\|/g, "#@@#").split('|');
            for (var k in exprArr) {
                if (exprArr[k].replace) // IE 5.x fix from Igor Poteryaev.
                    exprArr[k] = exprArr[k].replace(/#@@#/g, '||');
            }
            funcText.push('_OUT.write(');
            emitExpression(exprArr, exprArr.length - 1, funcText); 
            funcText.push(');');
            endExprPrev = endExpr;
            endMarkPrev = endMark;
        }
        emitText(line.substring(endExprPrev + endMarkPrev.length), funcText); 
    }
    
    var emitText = function(text, funcText) {
        if (text == null ||
            text.length <= 0)
            return;
        text = text.replace(/\\/g, '\\\\');
        text = text.replace(/\n/g, '\\n');
        text = text.replace(/"/g,  '\\"');
        funcText.push('_OUT.write("');
        funcText.push(text);
        funcText.push('");');
    }
    
    var emitExpression = function(exprArr, index, funcText) {
        // Ex: foo|a:x|b:y1,y2|c:z1,z2 is emitted as c(b(a(foo,x),y1,y2),z1,z2)
        var expr = exprArr[index]; // Ex: exprArr == [firstName,capitalize,default:"John Doe"]
        if (index <= 0) {          // Ex: expr    == 'default:"John Doe"'
            funcText.push(expr);
            return;
        }
        var parts = expr.split(':');
        funcText.push('_MODIFIERS["');
        funcText.push(parts[0]); // The parts[0] is a modifier function name, like capitalize.
        funcText.push('"](');
        emitExpression(exprArr, index - 1, funcText);
        if (parts.length > 1) {
            funcText.push(',');
            funcText.push(parts[1]);
        }
        funcText.push(')');
    }

    var cleanWhiteSpace = function(result) {
        result = result.replace(/\t/g,   "    ");
        result = result.replace(/\r\n/g, "\n");
        result = result.replace(/\r/g,   "\n");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, '$1'); // Right trim by Igor Poteryaev.
        return result;
    }

    var scrubWhiteSpace = function(result) {
        result = result.replace(/^\s+/g,   "");
        result = result.replace(/\s+$/g,   "");
        result = result.replace(/\s+/g,   " ");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, '$1'); // Right trim by Igor Poteryaev.
        return result;
    }

    // The DOM helper functions depend on DOM/DHTML, so they only work in a browser.
    // However, these are not considered core to the engine.
    //
    TrimPath.parseDOMTemplate = function(elementId, optDocument, optEtc) {
        if (optDocument == null)
            optDocument = document;
        var element = optDocument.getElementById(elementId);
        var content = element.value;     // Like textarea.value.
        if (content == null)
            content = element.innerHTML; // Like textarea.innerHTML.
        content = content.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
        return TrimPath.parseTemplate(content, elementId, optEtc);
    }

    TrimPath.processDOMTemplate = function(elementId, context, optFlags, optDocument, optEtc) {
        return TrimPath.parseDOMTemplate(elementId, optDocument, optEtc).process(context, optFlags);
    }
}) ();

TrimPath.parseTemplate_etc.modifierDef.url = document.myhands.Api.url;

