﻿function brpRouteDetailWidget(container){
	
	// properties
	var me=this;
	me.editOn = false;
    me.container = $(container);
    me.attrib = [];
    me.routeID = null;
    me.uploader = null;
    me.pics = [];
    me.scores = [];
    me.reviews = [];
    me.score =0;
    me.scorecnt =0;
    
    $('.detailmenu a', me.container).click(function(){ me.setPage(this.id.substring(4,5))}); 
    $('input#Btn_addAttr', me.container).click(function(){ me.setEditmode(2,true);});
    $('input#Btn_saveAttr', me.container).click(function(){ me.saveAttr();});        
    $('input#Btn_cancelAttr', me.container).click(function(){ me.setEditmode(2,false);});
    $('input#Btn_addScore', me.container).click(function(){ me.setEditmode(3,true);});
    $('input#Btn_saveScore', me.container).click(function(){ me.saveScore();});        
    $('input#Btn_cancelScore', me.container).click(function(){ me.setEditmode(3,false);});
    $('input#Btn_addPicture', me.container).click(function(){ me.setEditmode(1,true);});
    $('input#Btn_cancelPicture', me.container).click(function(){ me.setEditmode(1,false);});
    $('input#Btn_savePicture', me.container).click(function(){ me.savePicture();});
    $('input#Btn_addReview', me.container).click(function(){ me.setEditmode(4,true);});
    $('input#Btn_cancelReview', me.container).click(function(){ me.setEditmode(4,false);});
    $('input#Btn_saveReview', me.container).click(function(){ me.saveReview();});
    $('input#Btn_beoordeel', me.container).click(function(){ me.setPage(3);});// me.saveScoreGeneral();});
    
    if(me.editOn) {
        $('#detaildescription_edit').show();
        $('input#descriptionsave', me.container).click(function(){ me.saveDescription();});  
    }
    else {
      $('#detaildescription_edit').hide();
      $('#descriptionedit').hide();  
      $('#descriptionsave').hide();
    }
    
    me.getAttr();
    me.getScores();
    
    //me.createUploader();
    me.addHiddenForm();
    
}

brpRouteDetailWidget.prototype.addHiddenForm = function(){

	$(this.container).append('<form method=post action="" id="FrmDetail" name="FrmDetail" target="detailresponse" style="display:none; width:0px; height:0px;"><input type=hidden id="RouteID" name="RouteID" value=""/><input type=hidden id="Description" name="Description" value=""/></form>');
	$(this.container).append('<iframe id="detailresponse" name="detailresponse" src="about:blank" style="display:none; width:0px; height:0px"></iframe>'); 
}
brpRouteDetailWidget.prototype.renderPage = function(data,validIdx) {
    
    var me = this;
    me.routeID = data.RouteID;
    me.score = data.Score;
    me.scorecnt = data.ScoreCnt;
    $('input#detail_current_page').val(validIdx);
    $('.browser_title',me.container).html(data.RouteName);
    if ((data.Pictures) && (data.Pictures != ""))
        me.pics = data.Pictures.split("|");
    else
        me.pics = null;    
    me.populatePictures(me.pics); 

    $('#tdStart',me.container).html((data.StartPoint) ? data.StartPoint : 'onbekend');
    $('#tdDest',me.container).html((data.EndPoint) ? data.EndPoint : 'onbekend');
    $('#tdDist',me.container).html((data.RouteDist /1000) + ' km.');
    $('#tdTime',me.container).html(Math.round(data.RouteDist / 17000 * 60) + ' min.' );
       
    

    me.attrib = $.parseJSON(data.Attributes);
    me.populateAttr(me.attrib);
    me.scores = $.parseJSON(data.PartialScores);   
    me.populateScores(me.scores);
    me.reviews = $.parseJSON(data.Reviews);   
    me.populateReviews(me.reviews)
          
          
       
    $('#tdPicCnt',me.container).html((me.pics) ? '('+me.pics.length+')': '(0)');
    $('#tdReviewCnt',me.container).html((me.reviews)? '(' + me.reviews.length+')' : '(0)' );
    $('#tdDescr',me.container).html((data.Description) ? data.Description : 'Geen beschrijving beschikbaar.');

    if (me.editOn)
        $('#descriptionedit').val(data.Description);
         
    me.add_social_links();
    
    me.setPage(1);
    me.setEditmode(2,false);
    me.setEditmode(3,false);
    me.setEditmode(4,false);
    me.container.show();
    
   	//implement google tracking
	if (_gaq){
	    _gaq.push(['_trackEvent', 'Toon Optie', 'route detail']);
	    _gaq.push(['_trackEvent', 'Vaste route informatie', 'Toon route detail', data.RouteName]);
	}

}
brpRouteDetailWidget.prototype.setPage = function(pageIdx) {
    var me = this;
    $('.detailmenu a', me.container).removeClass('detailitem_on');
    $('.detailmenu a', me.container).addClass('detailitem');
    $('#page'+pageIdx, me.container).addClass('detailitem_on');
    $('div.detail_page', me.container).hide();
    $('div#detail_page' + pageIdx, me.container ).show();
    me.setEditmode(pageIdx,false);
}
brpRouteDetailWidget.prototype.setEditmode = function(pageIdx,isOn) {
    pageIdx = pageIdx *1;
    switch(pageIdx){
    case 1:
        if(isOn == true) { 
          $('div#gallery').hide();
          $('div#gallery_edit').show();  
        }
        else {
          $('div#gallery').show();
          $('div#gallery_edit').hide();  
        }  
        break;
    case 2:
       if(isOn == true) { 
        $('input#Btn_saveAttr').show();
        $('input#Btn_cancelAttr').show();
        $('input#Btn_addAttr').hide();
        $('input.attr_chk').attr('disabled',false);
        }
       else {
        $('input#Btn_saveAttr').hide();
        $('input#Btn_cancelAttr').hide();
        $('input#Btn_addAttr').show();
        $('input.attr_chk').attr('disabled',true);
       } 
       break;
    case 3:
       if(isOn == true) { 
        $('input#Btn_saveScore').show();
        $('input#Btn_cancelScore').show();
        $('input#Btn_addScore').hide();
        $(".myscores").stars({
		    inputType: "select",
		    disabled: false
	    });
        }
       else {
        $('input#Btn_saveScore').hide();
        $('input#Btn_cancelScore').hide();
        $('input#Btn_addScore').show();
        $(".myscores").stars({
		    inputType: "select",
		    disabled: true
	    });
       } 
       break;
    case 4:
       if(isOn == true) { 
        $('input#Btn_saveReview').show();
        $('input#Btn_cancelReview').show();
        $('input#Btn_addReview').hide();
        $('#detail_page4_edit').show();        
        }
       else {
        $('input#Btn_saveReview').hide();
        $('input#Btn_cancelReview').hide();
        $('input#Btn_addReview').show();
        $('#detail_page4_edit').hide();        
       } 
       break;          
    }

}
brpRouteDetailWidget.prototype.populatePictures = function(pics) {

    $('#picturelist',this.container).empty();
    if (pics){
    $.each(pics,function(i,p){
        var l = $('<li></li>');
        var a = $('<a href="'+frpImageUrl + p + '"></a>');
        a.attr('title','<a href="notok.html?src='+p+ '" target=_blank>Is deze foto niet OK ? meld het dan.</a>');
        a.append('<img src="'+frpThumbUrl+p+'" width="240" height="240" alt="" />');
        l.append(a);
        $('#picturelist',this.container).append(l);
        });
    }
    else
    {
        var l = $('<li></li>');
        var a = $('<a href="images/routelist/nophotolarge.jpg"></a>');
        a.append('<img src="images/routelist/nophotolarge.jpg" width="240" height="240" alt="" />');
        l.append(a);
        $('#picturelist',this.container).append(l);
    }    
    //create lightbox 
    $(function() {
        $('#gallery a').lightBox({
			imageLoading:			'images/lightbox/lightbox-ico-loading.gif',
			imageBtnPrev:			'images/lightbox/lightbox-btn-prev.gif',
			imageBtnNext:			'images/lightbox/lightbox-btn-next.gif',
			imageBtnClose:			'images/lightbox/lightbox-btn-close.gif',
			imageBlank:				'images/lightbox/lightbox-blank.gif',	
			txtImage:				'Afbeeling',
			txtOf:					'van'
        }
        );
    });        
}

//Attributes
brpRouteDetailWidget.prototype.getAttr = function() {
   var me = this;
   $.getJSON(frpgetAttrUrl + '&callback=?', {}, function(data, textStatus) { me.afterGetAttr(data, textStatus) });
};
brpRouteDetailWidget.prototype.afterGetAttr = function(data, textStatus) {
    if (data) {
       // this.attrGroups = data;  
        
        $('div#detail_page2_content').empty();
        
        var groupName = '';
        $.each(data,function(i,theAttr){
             if (groupName != theAttr.GroupName) {
                var h = (groupName == '') ? 'attrheader_first' : 'attrheader';
                var header = $('<div class='+ h +'>'+theAttr.GroupName + '</div>');
                
                $('div#detail_page2_content').append(header);
                groupName = theAttr.GroupName;
             }
             var el = $('<div class=attrcel></div>');
                 el.append($('<span class="attr_name"></span>').html(theAttr.AttrName));   
                 el.append($('<input class="attr_chk" type="checkbox" id="CB'+theAttr.AttrId+'" value="'+theAttr.AttrId+'" disabled>'));
                 el.append($('<span class="attr_explain" id="explain'+theAttr.AttrId+'">bla</span>'));
             $('div#detail_page2_content').append(el);                                  
        });  
    }    
}
brpRouteDetailWidget.prototype.populateAttr = function(attr) {
    
    $('span.attr_explain').empty();
    $('input.attr_chk').attr('checked',false);
    $('input.attr_chk').attr('disabled',true);
    $('input.attr_chk').attr('value','');
    if (attr) {
        $.each(attr,function(i,theAttr){
          if (theAttr.Pro > theAttr.Con)
            $('input#CB'+theAttr.Id).attr('checked',true);
          $('input#CB'+theAttr.Id).attr('value',theAttr.Pro + '|' +theAttr.Con);  
          $('span#explain'+theAttr.Id).html('(<i class="pro" alt="'+theAttr.Pro+' mensen stemmen voor" title="'+theAttr.Pro+' mensen stemmen voor">' + theAttr.Pro +'</i>&nbsp;|&nbsp;<i class="against" alt="'+theAttr.Con+' mensen stemmen tegen" title="'+theAttr.Con+' mensen stemmen tegen">' + theAttr.Con +'</i>)');
        });
    }
}

brpRouteDetailWidget.prototype.saveAttr = function() {
    
    function AttrInfo(Id,p,c) {
        var me =this;
        me.Id = Id;
        me.Pro = p;
        me.Con = c;
    }
    
    var me = this;
    if (!me.attrib)
        me.attrib = [];
    me.attrib.length =0;
    $('input.attr_chk').each( function(){
        var z = $(this).attr('value').split('|');
        var p = z[0];
        if(!p) p=0;
        var c = z[1];
        if(!c) c=0;
        if ($(this).attr('checked')) p++; else c++;
        var Id = this.id.substring(2,16);
        me.attrib.push(new AttrInfo(Id,p,c));
    });
    $.getJSON(frpsetRouteAttrUrl + '&callback=?', {'RouteID': me.routeID,'attrib':$.toJSON(me.attrib)},null);
    
    me.populateAttr(me.attrib);            
    
    me.setEditmode(2,false);
}

//Scores
brpRouteDetailWidget.prototype.getScores = function() {
   var me = this;
   $.getJSON(frpgetScoreUrl + '&callback=?', {}, function(data, textStatus) { me.afterGetScores(data, textStatus) });
}
brpRouteDetailWidget.prototype.afterGetScores = function(data, textStatus) {
    if (data) {
        var me = this;
        $('div#detail_page3_content').empty();
        var table = $('<table class="score_table"></Table>'); 
        $.each(data,function(i,theScore){
            var row = $('<tr></tr>');
            var h = (i == 0) ? 'attrheader_first' : 'attrheader';
            var header = $('<div class='+ h +'>'+theScore.ScoreName + '</div>');
            row.append($('<td colspan="4"></td>').append(header));
            table.append(row);
            row = $('<tr></tr>');           
            row.append($('<td>'+theScore.ScoreMinDescr+'</td>'));
            row.append($('<td></td>').append(me.createStar(theScore.ScoreId,theScore.ScoreMinValue,theScore.ScoreMaxValue)));               
            row.append($('<td>'+theScore.ScoreMaxDescr+'</td>'));
            row.append($('<td><span class="scoreCnt" id=tdScoreCnt'+theScore.ScoreId+'>(3)</span></td>'));                              
            table.append(row);             
        });  
        $('div#detail_page3_content').append(table);
        
        $(".myscores").stars({
		    inputType: "select",
		    disabled: true
	    });                                  
    }    
}
brpRouteDetailWidget.prototype.createStar = function(id,minv,maxv) {
    var div = $('<div class="myscores" id="score'+id+'"></div>');
    var op = '<select name="rate">';
    for(var i=minv; i<=maxv;i++) {
        op += '<option value="'+i+'" />'+i+'</option>';
    }
    op+='</select>';
    div.append(op);
    return div;
}

brpRouteDetailWidget.prototype.populateScores = function(scores) {
    var me=this;
    $('.myscores').stars("selectID", -1); 
    $('.scoreCnt').html('(0)');
    $('#score_general').stars("selectID", -1);
    $('#tdScoreCnt').html('(0)');             
    if(scores)
    {
        $.each(scores,function(i,theScore){
            if(theScore.ID=="1"){
              theScore.Score = me.score;
              theScore.Cnt =  me.scorecnt;
            }  
            var Sc =theScore.Cnt==0 ? 0 : Math.round(theScore.Score /theScore.Cnt);
            $('#score'+theScore.ID).stars("selectID", Sc-1);
            $('#tdScoreCnt'+theScore.ID).html('('+theScore.Cnt+')'); 
            if(theScore.ID=="1"){
              $('#score_general').stars("selectID", Sc-1);
              $('#tdScoreCnt').html('('+theScore.Cnt+')');             
            }
        });
    }
}
brpRouteDetailWidget.prototype.saveScoreGeneral = function() {
    var me = this;
    $.getJSON(frpsetScoreUrl + '&callback=?', {'RouteID': me.routeID,'Score':me.score ,'ScoreCnt':me.scorecnt},null);
}
brpRouteDetailWidget.prototype.saveScore = function() {

    function NewEl(Id,Sc){
        this.ID = Id;
        this.Cnt =1;
        this.Score = 1 * Sc;
    }
    
    function ScoreInfo(Id,Sc1){
       var Sc = parseInt(Sc1); 
       if (Sc >=1)
       { 
           var found =false; 
           if(me.scores) {
              for(var i=0; i < me.scores.length;i++) {
                if (me.scores[i].ID == Id)
                {
                    me.scores[i].Score += 1 * Sc;
                    me.scores[i].Cnt += 1; 
                    if (Id == "1"){
                      me.score = me.scores[i].Score;
                      me.scorecnt = me.scores[i].Cnt;                
                    }
                    found = true;               
                }
              }
           }
           else
             me.scores = [];       
     
           if (!found) {
             me.scores.push(new NewEl(Id,Sc));
             if (Id == "1"){
               me.score = Sc;
               me.scorecnt = 1;                
             }
           }
       }                
    }
    var me=this;
    $('.myscores').each(function(){
        ScoreInfo(this.id.substring(5,9),$('input',this).val());
    });
    
    $.getJSON(frpsetRouteScoreUrl + '&callback=?', {'RouteID': me.routeID,'scores':$.toJSON(me.scores)},null);
    
    me.saveScoreGeneral();
    me.populateScores(me.scores);
    me.setEditmode(3,false);
}

//Reviews 
brpRouteDetailWidget.prototype.populateReviews = function(reviews) {
    var me=this;
    $('#detail_page4_content').empty(); 
    if(reviews){
        $.each(reviews,function(i,rev){
            var h = (i == 0) ? 'attrheader_first' : 'attrheader';
            var header = $('<div id ="Rev'+rev.ID+'" class="RevBtn '+ h +'">('+rev.date+')&nbsp;-'+rev.Owner + '</div>');            
            me.GetReview(rev.ID);
            $('#detail_page4_content').append(header);
        });
    }
}
brpRouteDetailWidget.prototype.GetReview = function(Id) {
  var me = this;  
  $.getJSON(frpgetRouteReviewUrl + '&callback=?', {'RevID':Id},function(data, textStatus) { me.afterGetReview(data, textStatus,Id) });
}
brpRouteDetailWidget.prototype.afterGetReview = function(data,textStatus,Id) {
  var me = this;  
  $('div#Rev'+Id).after($('<P>'+data+'</P>'));
  me.setEditmode(4,false);    
}

brpRouteDetailWidget.prototype.saveDescription = function(){
    var me = this;
    var str = $('#descriptionedit').val();
    
    while(str.indexOf("\n") >= 0) {
        str = str.replace("\n","<BR>");
    }
    me.setDescription(str);
}

brpRouteDetailWidget.prototype.setDescription = function(descr){
    var me = this;
    $("#FrmDetail").attr("action",frpsetDescriptionUrl);
    $("#Description").val(descr);
    $("#RouteID").val(me.routeID);
    $("#FrmDetail").submit();
    me.afterSetDescription(descr,"suc");    
    //$('#tdDescr').html($('#descriptionedit').val());
  //  $.getJSON(frpsetDescriptionUrl + '&callback=?', {'Description':descr,'RouteID': me.routeID},function(data, textStatus) { me.afterSetDescription(data, textStatus) });
}
brpRouteDetailWidget.prototype.afterSetDescription = function(data,textStatus) {
    var me = this;
    $('#tdDescr').html(data);
}

brpRouteDetailWidget.prototype.saveReview = function() {
  var me = this;  
  me.SetReview($('#review_name').val(),$('#review_content').val());    
}

brpRouteDetailWidget.prototype.SetReview = function(theOwner,theContent) {
  var me = this;  
  $.getJSON(frpsetRouteReviewUrl + '&callback=?', {'RevOwer':theOwner,'RevContent':theContent},function(data, textStatus) { me.afterSetReview(data, textStatus,theOwner) });
}
brpRouteDetailWidget.prototype.afterSetReview = function(data,textStatus,theOwner) {
 function NewRev(Id,Owner){
    var now = new Date();
    now.setDate(now.getDate());
    this.ID = Id;
    this.date = now.toLocaleDateString();
    this.Owner = Owner;
 }   
 
 var me = this;
 if (me.reviews) {
    me.reviews.splice(0, 0, new NewRev(data,theOwner));    
 }
 else
 {
   me.reviews = [];
   me.reviews.push( new NewRev(data,theOwner));    
 }
 $.getJSON(frpsetRouteRevUrl + '&callback=?', {'RouteID': me.routeID,'rev':$.toJSON(me.reviews)},null);
 me.populateReviews(me.reviews);
 
}

//picture stuff
brpRouteDetailWidget.prototype.createUploader = function(){
            var me = this;            
            me.uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader-demo1'),
                action: frpsetRoutePicUrl,
                params:{FName:'test.txt',
                        RouteID:0},
                sizeLimit: 3 * 1024 * 1024, 
                minSizeLimit: 10,
                allowedExtensions:  ['jpg', 'jpeg', 'png', 'gif'],
                messages: {
                    typeError: "{file} geen goed bestandstype. Alleen {extensions} zijn toegestaan.",
                    sizeError: "{file} is te groot, de maximale grootte is {sizeLimit}.",
                    minSizeError: "{file} is te klein, minimale grootte is {minSizeLimit}.",
                    emptyError: "{file} is leeg, selecteer opniew.",
                    onLeave: "De foto wordt nu verwerkt als de pagina nu verlaten wordt wordt de actie geannuleerd."            
                },
                debug: true,
                onSubmit:function(id, fileName){
                    me.uploader.setParams({'FName':fileName,'RouteID':me.routeID});
                    },
                onComplete:function(id, fileName){
                    //rlw.getRouteList();
                    lsw.getRoute(me.routeID,'A');
                }                    
            });           
        }

brpRouteDetailWidget.prototype.savePicture = function() {
    var frm = $('form#frmfile');    
    var me = this;
    $('#fRouteID').val(this.routeID);
    frm.attr('action',frpsetRoutePicUrl);
    frm.submit();
    alert('Uw foto is succesvol toegevoegd. De volgende keer dat u de fietsrouteplanner raadpleegd wordt de foto getoond.');
    this.setEditmode(1,false);
}


brpRouteDetailWidget.prototype.add_social_links = function(){
    $('div#sobo').empty();
    var str_bookmarks='';
    var str_url_full='';
    var str_sb_entry;
    var str_sb_template='<a id="replace_id" href="replace_url" url="replace_url" title="Deel deze route op replace_name" rel="nofollow" class="viewbox replace_class" target="_blank"></a>';
    var str_url_coded=document.URL + '?RouteID='+this.routeID;
    str_url_coded=str_url_coded.replace('#','');
    var str_title_coded=$('.browser_title',this.container).html();
    var str_txt_coded='Een mooie route: '+str_title_coded;
    var arr_bm=new Array();
    arr_bm[0]=new Array("NUjij",1,1,"http://nujij.nl/jij.lynkx","?t=replace_title&u=replace_url&b=replace_txt");
    arr_bm[1]=new Array("Hyves",1,2,"http://www.hyves.nl/profilemanage/add/tips/","?name=replace_title&text=replace_txt replace_url&type=10&rating=5");
    arr_bm[2]=new Array("Facebook",1,3,"http://www.facebook.com/sharer.php","?u=replace_url");
    arr_bm[3]=new Array("Twitter",1,4,"http://twitter.com/home","?status=replace_title:+replace_url");
    arr_bm[4]=new Array("Digg",1,5,"http://digg.com/submit","?phase=2&url=replace_url&title=replace_title&bodytext=replace_txt");
    arr_bm[5]=new Array("Google Bookmarks",1,6,"http://www.google.com/bookmarks/mark","?op=add&bkmk=replace_url&title=replace_title&annotation=replace_txt");
    arr_bm[6]=new Array("Stumble it!",1,7,"http://www.stumbleupon.com/submit","?url=replace_url&title=replace_title&language=NL");
    arr_bm[7]=new Array("Del.icio.us",1,8,"http://del.icio.us/post","?v=4;url=replace_url;title=replace_title");
    arr_bm[8]=new Array("Symbaloo",1,9,"http://www.symbaloo.com/nl/add/","url=replace_url&title=replace_title&icon=http://www.okokorecepten.nl/i/socialbookmarks/symbaloo.gif");
    arr_bm[9]=new Array("LinkedIn",1,10,"http://www.linkedin.com/shareArticle","?mini=true&url=replace_url&title=replace_title&summary=replace_txt&source=falk");
    arr_bm[10]=new Array("eKudos",1,11,"http://www.ekudos.nl/artikel/nieuw","?url=replace_url&title=replace_title&desc=replace_txt");
    arr_bm[11]=new Array("MySpace",1,12,"http://www.myspace.com/Modules/PostTo/Pages/","?u=replace_url&t=replace_title");
    for(var i=0;i<arr_bm.length;i++){
        if(arr_bm[i][1]==1){
            str_url_full=arr_bm[i][3]+arr_bm[i][4];
            str_url_full=str_url_full.replace(/replace_title/g,escape(str_title_coded));
            str_url_full=str_url_full.replace(/replace_url/g,escape(str_url_coded));
            str_url_full=str_url_full.replace(/replace_txt/g,escape(str_txt_coded));
			str_url_full=str_url_full.replace(/replace_id/g,escape(str_txt_coded));
            str_sb_entry=str_sb_template;
            str_sb_entry=str_sb_entry.replace(/replace_name/g,arr_bm[i][0]);
            str_sb_entry=str_sb_entry.replace(/replace_url/g,str_url_full);
            str_sb_entry=str_sb_entry.replace(/replace_class/g,'cl_'+arr_bm[i][2]);
            str_bookmarks+=str_sb_entry
         }
    }
    $('div#sobo').append('<b>Deel deze route op...</b><br/>'+str_bookmarks);
}
