var curWin=Ti.UI.currentWindow;
curWin.barImage = '../images/Title_bar.png';

var doProfileRefresh = true;

//create a Map button in navigation bar When previous screen is Report
var Mapbtn = Ti.UI.createButton({
	backgroundImage:'../images/button_small_top.png',
	width:62,
	height:33,
	title:'Map',
	font:{fontSize:13,fontWeight:'bold',fontFamily:'Arial'},
});

// add plus button in navigation controller 
var plus = Ti.UI.createButton({
	backgroundImage:'../images/button_fish_plus.png',
	contentMode:'center',
	width:61,
	height:32,
})

//Create a navigation button it will placed When previous screen is ReportDetail
var closeBtn = Ti.UI.createButton({
	title:'Report Details',
	backgroundImage:'../images/resources_87.png',
	font:{fontSize:13,fontWeight:'bold',fontFamily:'Arial'},
	width:115,
	height:33,
})

	if(curWin.name=='reportDetail')
	{
		curWin.rightNavButton = Mapbtn;
		curWin.leftNavButton =closeBtn;
		nextWinName = curWin.name;
	}
	else
	{
		curWin.rightNavButton = plus;
		curWin.leftNavButton = Mapbtn;
	}

//All the bulk piece of work is here to start
Ti.include('CachedImage.js');
Ti.include('dateFormat.js');
Ti.include("TableViewActivity.js");

var nextWinName = 'profile';
var tablerows = [];

var parentView = Ti.UI.createView({
	left:0,
	top:0,
	width:320,
	height:'auto',
	layout:'vertical'
});

//curWin.layout = 'vertical';
var  refreshList = true;
var temparr = [];

//////alert(Ti.App.userLog);
curWin.BackgroundColor='#fff';
Titanium.UI.iPhone.statusBarStyle = Titanium.UI.iPhone.StatusBar.OPAQUE_BLACK;

Mapbtn.addEventListener('click', function(e)
{
	var mapWin = Ti.UI.createWindow({
		title:'Profile',
		url:'Map.js',
		param:arr,

	});
	mapWin.open({modal:true,animate:false});
});

closeBtn.addEventListener('click', function(e)
{
	Ti.UI.currentWindow.close();
});

plus.addEventListener('click',function(){
	var win = Titanium.UI.createWindow({
			url:'../view/Add_Edit_Report.js',
			barColor:'#111',
 			backgroundColor:'#fff',
 			tabBarHidden:true,
 			param:'null',
 			barImage:'../images/Title_bar.png'
	});
	Titanium.UI.currentTab.open(win,{animated:true});
});

//create a profile view
var profileuser_View1 = Ti.UI.createView({
	top:0,
	left:0,
	height:80,
	//width:100,
	backgroundGradient:{type:'linear',colors:[{color:'#977859',position:0.0},{color:'#774F27',position:1.0}]}
});

var container =  Titanium.UI.createView({
	  height:70,
	  width:90,
	  left:5, 
	  //top:2,
	  borderRadius: 0
});
		
var profileimage = Ti.UI.createImageView({
	    height:'auto',
		width:'auto',
		canScale:'false', 
		clipsToBounds: true, 
		aspectFill:true, 
		_parent:container,
		myId:0	 
});
container.add(profileimage);
profileuser_View1.add(container);

//create a profile view
var profileuser_View2 = Ti.UI.createView({
	top:0,
	left:100,
	height:80,
	width:200,
	backgroundColor:'#00000000',	
});
profileuser_View1.add(profileuser_View2);

var profile_user_name = Ti.UI.createLabel({left:5,top:10,text:Ti.App.userName,color:"#fff",width:200,height:20,font:{fontWeight:'bold',fontSize:18}})
profileuser_View2.add(profile_user_name);

var userName = Ti.UI.createLabel({left:5,top:32,text:'',color:"#fff",width:200,height:20,font:{fontWeight:'normal',fontSize:13}})
profileuser_View2.add(userName);

var user_Location = Ti.UI.createLabel({left:5,top:47,text:"",color:"#fff",width:200,height:20,font:{fontWeight:'normal',fontSize:13}})
profileuser_View2.add(user_Location);

var label=Ti.UI.createLabel({
	text:"You haven't posted any Report Yet! \n Tap the ✚ button above to get started.",
	textAlign:'center',
	color:'#000',
	top:-150
});

var arr = [];

var scrollView = Ti.UI.createScrollView({top:0,contentHeight:'auto',contentWidth:'auto',height:288,width:320});
var tableView = Ti.UI.createTableView({top:0, separatorColor:"#2e3e41",  searchHidden:false, scrollable: true});
scrollView.add(tableView);

var search = Titanium.UI.createSearchBar({ left:0, top:0, height:44, width:320, hintText:'Search Reports',/* value:'',*/ visible:true, backgroundColor:"#774F27", barColor:"#774F27"/*,showCancel:true*/});
search.backgroundGradient = {type:'linear',colors:[{color:'#977859',position:0.0},{color:'#774F27',position:1.0}]};

search.addEventListener('cancel', function(e){
	search.value = '';
	search.showCancel = false;
	search.blur();
	temparr = [];
	profileuser_View1.height = 80;
	scrollView.height = 372 - profileuser_View1.height;
	temparr = arr;
});
search.addEventListener('return', function(e){
	search.blur();	
});
search.addEventListener('change', function(e){
	if(search.value != '')
	{
		search.showCancel = true;    
		temparr = [];
		for(var i = 0,k = 0; i < tablerows.length; i++)
		{	
			var result = (tablerows[i].children[1].text.toLowerCase()).search(search.value.toLowerCase());
			
			if(result!=-1)
			{
				temparr[k] = tablerows[i];
				k++;
			}
		}  
		setSearchData(temparr);
	}
	else
	{
		setSearchData(tablerows);
	}
});
//=======

var Headrow = Ti.UI.createTableViewRow({});
tableView.add(search);
	
var xhr;
var json;
var response;

curWin.add(parentView);
function getReportlist()
{
	//List & populating data on this. 
	(This includes all the Client's data or php web Services So hidden from the security purpose)
	
	UserData()
	setData();

};

curWin.addEventListener('focus',function(e)
{
		
	if(doProfileRefresh)
	{
		getReportlist();
		doProfileRefresh = false;
		Ti.App.fireEvent('donRefreshSettings',{});
		search.showCancel = false;
	}
	else
	{
		doProfileRefresh = true;
		Ti.App.fireEvent('donNotRefresh',{});
	}
	
	if(Ti.App.openReport)
	{
		var win1 = Titanium.UI.createWindow({  
		   		title:'Report Details',
		   		name:nextWinName,
		    	url:'Report_Details.js',
		    	barColor:'#111',
		    	backgroundColor:'#fff',
		    	param:Ti.App.selectedReportId
    	});
    	
   		Ti.App.tabGroup.activeTab.open(win1, {
			animated : false
		});
    	
    	Ti.App.selectedReportId = 0;
		Ti.App.openReport = false;
	}
});

//getReportlist();
function setData()
{ 
	tableView.setData(data);
}

function replaceString(oldS, newS, fullS)
{
	    // Replaces oldS with newS in the string fullS
	    for (var i = 0; i < fullS.length; i++)
	    {
	        if (fullS.substring(i, i + oldS.length) == oldS)
	        {
	            fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
	        }
	    }
	    return fullS;
}

function sortByDate(a, b) {
    var x = a.data.created.substr(0,a.data.created.length-10);
    var y = b.data.created.substr(0,b.data.created.length-10);
    var x1  = new Date(x);
    var y1 = new Date(y); 
    if(Ti.App.isValidDate(x1)==false)
    {
        x1 = new Date(a.data.created);
    }
    if(Ti.App.isValidDate(y1)==false)
    {
        y1 = new Date(b.data.created);
    }
    return ((x1 > y1) ? -1 : ((x1 < y1) ? 1 : 0));
}

function findString(oldS, fullS)
{
	for (var j = 0; j < fullS.length; j++)
    {
    	if (fullS.substring(j, j + oldS.length) == oldS)
        {
			 return 1;
        }
    }
    return 0;
}  

//get the data for the for the Profile name location & username
function UserData()
{
};
//======
function setSearchData(arry)
{ 	
	var data = [];
	var flag = true;
	data.push(Headrow);
	
	var totalHeight=44;
	
	for (i=0;i<arry.length;i++)
	{
		var row = null;
		
		var str = arry[i].date.substr(0,arry[i].date.length-18);
		var createdate = new Date(str);
		var isDate = Ti.App.isValidDate(createdate);
        
        if(isDate==false)
        { 
            str = arry[i].date;
            createdate = new Date(str);
        }
 		var monthString = createdate.format('mmmm');
        var month = createdate.getMonth()+1;
        var date = createdate.getDate();
 		var fullyear =  createdate.getFullYear().toString();      
 		var year = createdate.getFullYear().toString().substr(2,2);
        
        if(month<10)month = '0'+ month;
        if(date<10)date = '0'+ date;
        
 		var newdatestr = month+'/'+date+'/'+year;
 		
		if(flag)
		{  
			var hv = Titanium.UI.createLabel({
    			height:23, 
   			 	text:'\t'+monthString+' '+fullyear,
   			 	color:'white',
   			 	font:{fontSize:12}
			});
			hv.backgroundGradient = {type:'linear',colors:[{color:'#938171',position:0.0},{color:'#79695C',position:1.0}]};

			var section = Titanium.UI.createTableViewSection({
    			height: 40,
  		  		headerView: hv
			});
			data.push(section);
			totalHeight+=40;
 			flag = false;
		}
		if(i < arry.length-1)
		{   
			var tempstr  = new Date(arry[i+1].date);
			if(tempstr.getMonth()+1 == Math.abs(month) && tempstr.getFullYear() == Math.abs(fullyear))
			{
				flag = false;
			}
			else
			{
				flag = true;
			}
		}
		
		totalHeight+=70;
		
		var row = arry[i];
 		data.push(row);
	}
	
	tableView.setData(data);

}

search.addEventListener('focus', function(e){
	profileuser_View1.height = 0;
	scrollView.height = 372 - profileuser_View1.height;
	search.showCancel = true;
})

search.addEventListener('click', function(e){
	profileuser_View1.height = 0;
	scrollView.height = 372 - profileuser_View1.height;
})

Ti.App.addEventListener('donNotProfileRefresh',function(e){
	doProfileRefresh = false;
});

Ti.App.addEventListener('doRefresh',function(e){
	doProfileRefresh = true;
});

parentView.add(profileuser_View1);
parentView.add(scrollView);
function addTheViewToProfile()
{
	curWin.add(parentView);
}

animateContainer.add(imageView2);

//Add the image for both the imageViews
if(Ti.App.profileImage!='' && Ti.App.profileImage!=null)
{
	cachedImageView(Ti.App.profileImage, profileimage);
}