/*
 * Ext JS Library 2.0 Beta 1
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
// reference local blank image
Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif';

var winC;
var storeC;
var panelTitleC=null;
function setCookie(name, value, expires) {
    setCookieAlways(name, value);
}
function setCookieAlways(name, value) {
    var expires = new Date();
    expires.setFullYear(expires.getFullYear()+10,expires.getMonth(),1);
    document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1)
        { 
            c_start=c_start + c_name.length+1 
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        } 
    }
    return ""
}
function saveClick(id, url, root_url) {
    //save id to cookie
    if ( typeof( isHomePage ) != 'undefined' && isHomePage == true && getCookie('challengePoll').length==0 ) {
        setCookie("challengePoll",id);
        //save to server and then open the poll results
        var storeR = new Ext.data.JsonStore({
            url: root_url+'PollHandler.aspx?challengePoll='+id,
            root: 'challenges_votes',
            fields: ['id', 'votes'],
            id: 'id',
            autoLoad: true
        });
        storeR.on('load',processResults);
        storeR.on('loadexception', failedResults);
    } else
      window.location = url;
}
function processResults( storeR, /*Ext.data.Record[] */records, /*Object */options) {
    //alert("there are some results!");
    for( i=0; i<storeC.getTotalCount(); i++ ) {
        var challengeRecord = storeC.getAt(i);
        var voteRecord = storeR.getById(challengeRecord.get('id'));
        if ( voteRecord ) {
            challengeRecord.set('votes', parseInt(voteRecord.get('votes')));
            challengeRecord.set('votesText', "<b>Votes: "+voteRecord.get('votes')+"</b>");
        } else {
            challengeRecord.set('votes', 0);
            challengeRecord.set('votesText', "<b>Votes: 0</b>");
        }
    }
    
    storeC.sort( 'votes', 'DESC');
    if ( panelTitleC ) {
        Ext.DomHelper.overwrite(panelTitleC.body,"<div class='wdytHeader'>Voting Results:</div>");
    }
}
function failedResults() {
    //alert("failed!");
    alert("Thank you for your vote.");
    winC.close();
}

Ext.onReady(function(){
    var xd = Ext.data;
    Ext.QuickTips.init();

    storeC = new Ext.data.SimpleStore ({
        data: (typeof(challenges_data)!='undefined')?challenges_data: [],
        fields: ['name', 'id', 'url', 'image_url', 'description','root_url','votes','votesText']
        //sortInfo: {field: 'name', direction: 'ASC'}
    });

    var tpl = new Ext.XTemplate(
		'<tpl for=".">',
            '<div class="thumb-wrap" id="challenge_{id}" ext:qtip="{description}" ext:qtitle="{name}" ext:qwidth="200">',
		    '<div class="thumb" ext:qtip="{description}" ext:qtitle="{name}" ext:qwidth="200"><a href="javascript:saveClick(\'{id}\',\'{url}\',\'{root_url}\')"><img src="{image_url}" ext:qtip="{description}" ext:qtitle="{name}" ext:qwidth="200"></a></div>',
		    '<div class="thumb" ext:qtip="{description}" ext:qtitle="{name}" ext:qwidth="200"><a href="javascript:saveClick(\'{id}\',\'{url}\',\'{root_url}\')"><span ext:qtip="{description}" ext:qtitle="{name}" ext:qwidth="200">{name}</span></a>',
		    '<br/><span ext:qtip="{description}" ext:qtitle="{name}" ext:qwidth="200">{votesText}</span></div>',
		    '</div>',
        '</tpl>',
        '<div class="x-clear"></div>'
	);

    var panels = [];
    if ( typeof( isHomePage ) != 'undefined' ) {
        panelTitleC = new Ext.Panel( {
            hideBorders: true,
            html: "<div class='wdytHeader'>Click on the engineering challenge you think is the most important:</div>",
            region: 'north',
            margins:'4 4 4 4' 
        });
        panels[panels.length] = panelTitleC;
    } else {
        panelTitleC = new Ext.Panel( {
            hideBorders: true,
            html: "<div class='wdytHeader2'>Find out more about any of these Grand Challenges:</div>",
            region: 'north',
            margins:'4 4 4 4' 
        });
        panels[panels.length] = panelTitleC;
    }
    var panel = new Ext.Panel({
        id:'challenges-popup',
        cls:'mainPanel',
        hideBorders: true,
        layout:'fit',
        region: 'center',
        margins:'0 0 0 0', 
            
        items: new Ext.DataView({
            store: storeC,
            tpl: tpl,
            autoHeight:true,
            multiSelect: false,
            overClass:'x-view-over',
            itemSelector:'div.thumb-wrap',
            emptyText: 'No challenges to display'

        })
    });
    panels[panels.length] = panel;
    winC = new Ext.Window({
        title: 'Engineering\'s Grand Challenges',
        closable:true,
        width:625,
        height:530,
        plain:true,
        layout: 'border',
        frame: false,

        items: panels
    });
    
    winC.on('close', function() {
        //save id to cookie
        if ( typeof( isHomePage ) != 'undefined' && isHomePage == true && getCookie('challengePoll').length==0 )
            setCookie("challengePoll","none");
    });

    if ( !(typeof( isHomePage ) != 'undefined' && isHomePage == true && getCookie('challengePoll').length>0 ) )
        winC.show();

});


