var callbacks = new Array();


$(document).ready(function() {
    initCufon();
    bindAjaxToTemplateView();
    bindAjaxSubmitToTemplateView();
    bindCloseOverlayToButton();
    bindCloseOverlayToEvents();
    addToCallbackQueue(initCufon);
    intiBuzzAutoReload();
});

function getContainer(obj)
{
    //assign temp reference for nested anon function
    //try to find parent container
    var container = $(obj).parents("div.template_container:first").find("[id^='template_container_']");
    if($(obj).hasClass('modalPopup'))
    {
        container = $("#template_container_modal");
    }
    if($(obj).hasClass('ciname'))
    {
        container = $("#template_container_cinema_listing");
    }
    return (container.length == 0) ? container = $("#template_container") : container = container.eq(0);  
}

function showProgressBar(obj)
{  
    $(obj).prepend('<div style="padding:5px;background:#000000;position:absolute;z-index:1;" class="progressBar"><img width="16" height="16" src="/assets/images/ajax-loader.gif" /></div>');
}

function hideProgressBar()
{
    $('.progressBar').hide();
}

function performAjax( object ) {
    var ob = this;
  
    if( typeof $(object).attr('href') == 'string' )
    {
        ob = object;
    }
  
    var container = getContainer(ob);
    var paramsStr = $(ob).attr('rel');
    var paramsObj = jQuery.parseJSON( paramsStr );
  
    // override container if it has been specified as a additional param in links "rel" attribute
    if( paramsObj != null && paramsObj['container'] )
    {
        container = $("#"+paramsObj['container']);
    }

    // if we need a custom behaviour of a progress bar, 
    // it can be defined in a calling link's attribute "rel" 
    if( paramsObj != null && paramsObj['progressBarFunc'] )
    {
        // if additional param is defined, call the progress function defined
        var customFunc = paramsObj['progressBarFunc'];
        if( customFunc.length > 1 )
        {
            eval( customFunc + '()' );
        } 
        else
        {
            showProgressBar(container);
        }
    }
    else // otherwise call default progress bar function
    { 
        showProgressBar(container);
    }
  
    var url = processUrlForAjax( ob.href );
    
    $.ajax({
        url: url,
        dataType: "json",
        success: function(data) {
            if( typeof data == 'object' )
            {
                // content returned by backend
                if( data['html'] !== undefined )
                {
                    container.html( data['html'] );
                }
                // callback function returned by backend
                if( data['fnc'] !== undefined )
                {
                    var funcName = data['fnc'];
                    eval(funcName);
                }
            }
			
            bindAjaxToTemplateView(); 
            bindAjaxSubmitToTemplateView(); 
            //init all callbacks 
            for ( var i in callbacks ){ 
                if(typeof callbacks[i] == 'function') 
                { 
                    callbacks[i]( this ); 
                } 
            }                 
            return false;
        }
    });
  
    return false;
}

function performAjaxFormSubmit()
{ 
    var url = $(this).attr('action') + "?" + $(this).serialize();
    url = processUrlForAjax( url );
    var container = getContainer(this); 
    showProgressBar(container);
  
    $.post(  
        url,  
        $(this).serialize(),
        function( data )
        {     
            if( typeof data == 'object' )
            {
                // content returned by backend
                if( data['html'] !== undefined && !data['error'] )
                {
                    container.html( data['html'] );
                }
                if(data['error'])
                {
                    hideProgressBar();
                }
                // callback function returned by backend
                if( data['fnc'] !== undefined )
                {
                    var funcName = data['fnc'];
                    eval(funcName);
                }
            }
            bindAjaxToTemplateView();
            bindAjaxSubmitToTemplateView();
            //init all callbacks
            for ( var i in callbacks ){
                if(typeof callbacks[i] == 'function')
                {
                    callbacks[i]( this );
                }
            }
        },
        'json'
        );  
    return false;
}

function bindAjaxToTemplateView() {
    $("a.ajax_lnk").unbind( 'click', performAjax ).click( performAjax );
}

function bindAjaxSubmitToTemplateView()
{
    $("form.ajax_submit").unbind( 'submit', performAjaxFormSubmit ).submit( performAjaxFormSubmit );
}


function addToCallbackQueue(callback){
    callbacks.push(callback);
}

/**
 * Binds overlay close button click triggering
 * Binding affects all elements with class .closebutton
 * 
 * @return
 */
function bindCloseOverlayToButton()
{
    $(".closebutton").click(function(){
        triggerOverlayCloseButtonClick();
        return false;
    });
}

/**
 * Binds overlay close to ESC event
 * 
 * @return
 */
function bindCloseOverlayToEvents()
{
    $(document).keyup(function(e) {
        
        if (e.keyCode == 27) {
            triggerOverlayCloseButtonClick();
            return false;
        }   // esc
    });
}

function triggerOverlayCloseButtonClick()
{
    if($('#overlaycloselink'))
    {
        $('#overlaycloselink').trigger('click');
    }
}

function initCufon()
{
    Cufon.replace('.gs', {
        fontFamily: 'Gill Sans'
    });
    Cufon.replace('.gsub', {
        fontFamily: 'Gill Sans'
    });
    Cufon.replace('.gsub span', {
        fontFamily: 'Gill Sans'
    });
    Cufon.replace('ul.tabs-no li a', {
        fontFamily: 'Gill Sans Ultra Bold'
    });
        
    Cufon.replace(['.book_now h4','.most_populer h3','.film_tweet h3', '.film_tweet h3 small','.heading h3','.movies_list .section h3'], {
        fontFamily: 'GillSans',
        hover: true
    });
    Cufon.replace(['.book_now h4 strong','.most_populer h3 strong', '.film_tweet h3 strong','.movies_list .section h3 strong'], {
        fontFamily:'Gill Sans Ultra Bold',
        hover: true
    });
    Cufon.replace(['.search_bar strong', '.film_tweet .follow_btn span strong'], {
        fontFamily:'Gill Sans MT',
        hover: true
    });
    Cufon.replace(['#nav ul li a'], {
        fontFamily: 'Gill Sans MT',
        hover: true,
        textShadow: '1px 1px 2px #000'
    });
        
    Cufon.replace(['.available_on h4,.vedio_gallery h5,.image_gallery h5','.detail_icons h1'], {
        fontFamily: 'GillSans',
        hover: true
    });
    Cufon.replace(['#nav ul li a,.available_on .cinema .left a,.available_on .products ul li a strong'], {
        fontFamily:'Gill Sans MT',
        hover: true
    });
    Cufon.replace(['.available_on h4 strong,.vedio_gallery h5 strong,.image_gallery h5 strong','.detail_icons h1 strong'], {
        fontFamily:'Gill Sans Ultra Bold',
        hover: true
    });
    Cufon.replace(['#nav ul li a,.search_bar strong', '.film_tweet .follow_btn a strong'], {
        fontFamily:'Gill Sans MT',
        hover: true
    });
    Cufon.replace(['#nav ul li a'], {
        fontFamily: 'Gill Sans MT',
        hover: true,
        textShadow: '1px 1px 2px #000'
    });
      
}

function buzzRefresh()
{
    $('#buzz_refresh_btn').click();
}

function commentPanelRefresh()
{
    $('#comment_refres_btn').click();
}

function intiBuzzAutoReload()
{
    setInterval( "buzzRefresh()", 180000 );
}

function processUrlForAjax( url )
{
    var param_concatenator = '?';
    if ( url.match(/\?/g) )  param_concatenator = '&';
    return url + param_concatenator + 'rand=' + Math.ceil(Math.random()*10000) + '&ajax=1';
}

function showRatingGivenMsg()
{
    alert( 'You have given your vote to this film already' );
}


