function initHTML5(){document.createElement("header");document.createElement("section");document.createElement("footer");document.createElement("article");document.createElement("nav");}function scriptLoader(src,f){var head= document.getElementsByTagName('head')[0];var script= document.createElement('script');script.type= 'text/javascript';script.src= src;head.appendChild(script);if(typeof(f) == 'function'){f();}}function styleLoader(src){
var head= document.getElementsByTagName('head')[0];var style= document.createElement('link');style.type= 'text/css';style.href= src;style.rel = "stylesheet";head.appendChild(style);}
initHTML5();

/**Handles working with querystring and redirection*/
var page = {};page.redirect = function(href){var location = $('base').attr('href');window.location = location + href;};
//get a querystring value given the key
page.getQueryVariable = function(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return -1; 
};
//change a querystring variable defining both the key and value;
page.add_or_update_qs = function(key, value){
   var qs = window.location.search.substring(1); 
   var vars = qs.split("&");
   var vlen =  vars.length;
   var flag = false;
   
   if(typeof (window.location.toString().split("?")[1]) == 'undefined'){
       
        qs += value == "" ? "" : key+"="+value; 
   }
   else{
    
    for (var i=0;i<vlen;i++) {
        var pair = vars[i].split("=");
    
        if (pair[0] == key) {
            flag = true;
            qs = value == "" ? qs.replace(vars[i],""): qs.replace(vars[i],key+"="+value);
        }
    }
    if(flag == false){
        qs += value == "" ? "" : "&" +key+"="+value;
    } 
  }   
  return qs;
};

page.remove_qs_value = function(key, qs){
    
    var qstring;
    var newqs = "";
    
    if(typeof(qs) == 'undefined'){
        //get the querystring from the address bar
        if(typeof (window.location.toString().split("?")[1]) == 'undefined'){
            return ""; 
        }
        else{
            qstring = window.location.search.substring(1);
        }    
    }
    else{
        qstring = qs;
    }
     
    //now that we have the querystring, split by &
    var vars = qstring.split('&');
    var vlen = vars.length;
    var flag = false;

    for (var i=0;i<vlen;i++) {
        var pair = vars[i].split("=");
        //rebuild querystring
        if(pair[0] == key){
           //if this is the value remove it 
        }
        else{
            newqs += pair[0] + "=" + pair[1] + "&";
        }
    }
    return newqs.substring(0,newqs.length-1);
};

page.getBase = function(){
	return $('base').attr('href');
}

page.createCookie = function(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

page.readCookie = function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

page.eraseCookie = function(name) {
	createCookie(name,"",-1);
}

/*Site extensions for the new file-manager*/
var CMSExtension = {};

CMSExtension.StyleLoader = function (src){
    var head= document.getElementsByTagName('head')[0];var style= document.createElement('link');style.type= 'text/css';style.href= src;style.rel = "stylesheet";head.appendChild(style);
}
 
CMSExtension.InitLightBox = function(gsel, opt){
	
	if (typeof(opt.theme) == 'undefined'){
		opt.theme = 'white';
	}
	
	
	if($('script[src="../scripts/jquery-lightbox-0.5/js/jquery.lightbox-0.5.min.js"]').length == 0){
		$.getScript('../scripts/jquery-lightbox-0.5/js/jquery.lightbox-0.5.min.js',function(){
			//init lighbox theme options
			if(opt.theme == 'white'){
				$(gsel).lightBox({
			 		imageLoading: '../scripts/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',
                	imageBtnClose: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-close.gif',
                	imageBtnPrev: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-prev.gif',
                	imageBtnNext: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-next.gif'
				});				
			}
			else if(opt.theme == 'black'){
				$(gsel).lightBox({
			 		imageLoading: '../scripts/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',
                	imageBtnClose: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-close.gif',
                	imageBtnPrev: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-prev.gif',
                	imageBtnNext: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-next.gif'
				});				
			}
			else if(opt.theme == 'transparent'){
				$(gsel).lightBox({
			 		imageLoading: '../scripts/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',
                	imageBtnClose: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-close.gif',
                	imageBtnPrev: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-prev.gif',
                	imageBtnNext: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-next.gif'
				});			
			}
			else{
				$(gsel).lightBox({
			 		imageLoading: '../scripts/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',
                	imageBtnClose: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-close.gif',
                	imageBtnPrev: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-prev.gif',
                	imageBtnNext: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-next.gif'
				});
			}
		});
	}
	if($('link[href="../css/common/cmsfeatures.css"]').length == 0){
		CMSExtension.StyleLoader ('../css/common/cmsfeatures.css');
	}
	
	if(opt.theme == 'white'){
		//setting up the theme
		if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css"]').length == 0){
			CMSExtension.StyleLoader ('../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css');
			if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-black.css"]').length != 0){
				$('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-black.css"]').remove();}
			if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-transparent.css"]').length != 0){
				$('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-transparent.css"]').remove();}
		}
	}
	else if(opt.theme == 'black'){
		//setting up the theme
		if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css"]').length == 0){
			CMSExtension.StyleLoader ('../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-black.css');
			if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css"]').length != 0){
				$('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css"]').remove();}
			if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-transparent.css"]').length != 0){
				$('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-transparent.css"]').remove();}
		}
	}
	else if(opt.theme == 'transparent'){
		//setting up the theme
		if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-transparent.css"]').length == 0){
			CMSExtension.StyleLoader ('../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-transparent.css');
			if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-black.css"]').length != 0){
				$('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5-black.css"]').remove();}
			if($('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css"]').length != 0){
				$('link[href="../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css"]').remove();}
		}
	}
}

CMSExtension.RenderGallery = function(pos, op){
	switch (op.type){
		case 1:
		var o = {};
		o.gid = pos;
		o.type = op.type;
		o.opt = op.optimized
		o.desc = op.descriptions;
		o.lb = op.lightbox;
		o.si = op.singleimagegallery;
		o.theme = op.theme;

		//image gallery
			$.post('../common/cms/gallery/g.php',o,function(r){
				$('#gallery-holder-'+pos).html(r);
			});
		break;
		case 3:
		case 4:
		case 5:
			var o = {};
			o.gid = pos;
			o.type = op.type;
			o.desc = op.descriptions;
			o.title = op.titles;
			o.dlimage = op.downloadimage;
			
			$.post('../common/cms/gallery/g.php',o,function(r){
				$('#gallery-holder-'+pos).html(r);
				if($('link[href="../css/common/cmsfeatures.css"]').length == 0){
					CMSExtension.StyleLoader ('../css/common/cmsfeatures.css');
				}
			});
		break;	
	}

};

/*Site Extensions
* Only contain functions available to the frontend
* Backend functions are stored elsewhere in the cms.functions file 
*/
var Extensions = {
    
    
        StyleLoader: function (src){
        
        var head= document.getElementsByTagName('head')[0];var style= document.createElement('link');style.type= 'text/css';style.href= src;style.rel = "stylesheet";head.appendChild(style);
    
        },    
    
        RenderGallery : function (gallery_id, showraw, lightbox, oneimagegallery){
           /*the code that a user plugs in 
           * showraw = true - the raw images will be rendered!
           * eg 
           * <div class='gallery-holder' id='gallery-holder-1'></div>
           * <script>Extensions.RenderGallery(1,false,false,false);<script> 
           * functionality:
           * onpageload - request page : common/site/plugins/g.php
           * the page g.php will call on CMSGallery::renderImageGallery() and echo the result
           * the result will be loaded in the defined div above
           * 
           * Note:
           * oneimagegallery means only 1 image is visible and onlick of that image, the gallery
           * is launched via lightbox!!!!
           */
                /*
               * Check to see if the stylesheet is loaded 
               */
               
               if($('link[href="../css/common/cmsfeatures.css"]').length == 0){
                   Extensions.StyleLoader ('../css/common/cmsfeatures.css');
               }
               $.post('../common/cms/gallery/g.php',{act:3,gid:gallery_id,sr:showraw,lb:lightbox,og:oneimagegallery},function(r){
                    $('#gallery-holder-'+gallery_id).html(r);
               });
        },
        
        RenderProductGallery : function (gallery_id, showraw, lightbox, oneimagegallery){
           /*the code that a user plugs in 
           * showraw = true - the raw images will be rendered!
           * eg 
           * <div class='gallery-holder' id='gallery-holder-1'></div>
           * <script>Extensions.RenderGallery(1,false,false,false);<script> 
           * functionality:
           * onpageload - request page : common/site/plugins/g.php
           * the page g.php will call on CMSGallery::renderImageGallery() and echo the result
           * the result will be loaded in the defined div above
           * 
           * Note:
           * oneimagegallery means only 1 image is visible and onlick of that image, the gallery
           * is launched via lightbox!!!!
           */
                /*
               * Check to see if the stylesheet is loaded 
               */
               
               if($('link[href="../css/common/cmsfeatures.css"]').length == 0){
                   Extensions.StyleLoader ('../css/common/cmsfeatures.css');
               }
               $.post('../common/cms/gallery/g.php',{act:4,gid:gallery_id,sr:showraw,lb:lightbox,og:oneimagegallery},function(r){
                    $('#gallery-holder').html(r);
               });
        },
        
        ImageGallery : function (gid, val){
          /*renders either lightbox or window.open on image gallery!
          * This function is returned from g.php after RenderGallery is called
          * it thens calls either lightbox
          * $('#image-gallery-val ul li a').lightbox(options);
          * or 
          * A click handler which will append window.open to each anchor
          * and feed the href as the window's location!
          * $('#image-gallery-val ul li a').click(function(){});
          */

           if(val == 1){
               //lightbox
               $.get('../scripts/jquery-lightbox-0.5/js/jquery.lightbox-0.5.min.js',function(){
                   styleLoader('../scripts/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css');
                   $('#image-gallery-'+gid+" ul li a").lightBox({
                       imageLoading: '../scripts/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',
                       imageBtnClose: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-close.gif',
                       imageBtnPrev: '../scripts/jquery-lightbox-0.5/images/lightbox-btn-prev.gif',
                       imageBtnNext: '../scripts/jquery-lightbox-0.5//images/lightbox-btn-next.gif'
                   });
               });
           }
           else{
               
           }
            
        },
        
        /* Renders the related products */
        GetProductSuggestions: function(context, ses, $pid, $main_cat,$sub_cat,$brand,$cust1,$cust2,$cust3,$cust4,$page){
            
            $(context).html('Loading related products....');
            $.post('../common/store/requests/p.php',{ses:ses, pid:$pid,main_cat:$main_cat,sub_cat:$sub_cat,brand:$brand,cust1:$cust1,cust2:$cust2,cust3:$cust3,cust4:$cust4,page:$page},function(r){
                $(context).html(r);
            })
            
        }
};

var dateHelper = {
    
    datediff: function(date1, date2){
        //what is the difference between the 2 dates? (in days)
        return this.convertDateToNum(date1) - this.convertDateToNum(date2); 
    },
    
    isBefore: function(date1, date2){
       //is date1 before date2 
       if(this.convertDateToNum(date1)> this.convertDateToNum(date2)){
            return false;
        }else{
            return true;
        }
    },
    
    isAfter: function(date1, date2){
        //is date1 after date2
        if(this.convertDateToNum(date1)> this.convertDateToNum(date2)){
            return true;
        }else{
            return false;
        }
    },
    
    convertDateToNum: function(dt){
        var dateAsNum = dt;
        while (dateAsNum.indexOf('-',0) > -1){
            dateAsNum = dateAsNum.replace('-','');
        }
        return parseFloat(dateAsNum);
        
    },
    
    splitDate: function (dt){
        //determine if the date has a time
        if(dt.indexOf(':',0)>-1){
            //there is a time
            var fsplit = dt.split(' ');
            var ssplit = fsplit[0].split('-');
            var tsplit = fsplit[1].split(':');
            for(var i =0;i<tsplit.length;i++){
                ssplit.push(tsplit[i]);
            }
            return ssplit;
        }
        else{
            //there is no time only a date
            return dt.split("-");
        }      
    },
    
    chooseDate: function(sel){
        
        var eachId = sel.replace('#','');
        eachId = eachId.replace('.','');
        
        var h = $('#'+eachId+'-0').val()+"-"+$('#'+eachId+'-1').val()+"-"+$('#'+eachId+'-2').val()+" "+$('#'+eachId+'-3').val()+":"+$('#'+eachId+'-4').val();
        //right here we should validate the selection
        $(sel).val(h);
        
        this.closePicker(sel); 
    },
    
    closePicker: function (sel){
        $(sel+'-picker').remove();
    }
    
};

var DatePicker = function(sel, options){
    
    var selector = sel;
    var jqsel = $(selector);
    
    var eachId = sel.replace('#','');
    eachId = eachId.replace('.','');
    
    //get the current date and time
    var td = new Date();
    var dt_now = new Array();
    dt_now[0] = td.getFullYear();
    dt_now[1] = td.getMonth()+1;
    dt_now[2] = td.getDate();
    dt_now[3] = td.getHours();
    dt_now[4] = td.getMinutes();
    dt_now[5] = td.getSeconds();
    
   
    //set the default options
    var defaults = {
        minDate: dt_now[0]+"-"+dt_now[1]+"-"+dt_now[2],
        maxDate: (dt_now[0]+8)+"-"+dt_now[1]+"-"+dt_now[2],
        startDate: "",
        pickerType: "datetime",
        amtofyears:10
    };
    
     
    
    //merge with the user options
    var opts = $.extend(defaults,options);
    
    //the min and max dates
    var dt_min = dateHelper.splitDate(opts.minDate);
    var dt_max = dateHelper.splitDate(opts.maxDate);
    var dt_start = opts.startDate == "" ? dt_now : dateHelper.splitDate(opts.startDate);
    
    var dt = new Array();
    //dates/times will be stored in an array
    /*dt = 0 - day, 1 - month, 2 - year, 3 - hour, 4 - minutes, 5 - seconds
     * Potential options
     * > min date - yyyy-mm-dd
     * > max date - yyyy-mm-dd
     * > start date - "today"(default) - "date" (yyyy-mm-dd)
     * > pickertype - date | time | datetime 
     * ---------- Future
     * > dateformat
     * > timeformat
     * --------------
     * 
     * Notes: datepicker shows as a popup on focus on a field or by entering an onclick event and calling instance.showPicker();
     * The select element ids are the value of the initial selector with a - and number attached (referring to place in array)
     */

    return{
        
       
        renderPicker: function(){
           
            var def;
            
           if(opts.startDate == ''){
               //no defaults, default to todays date
               def = dt_now;
           }
           else{
               //default to whatever date is set (take into consideration the time as well as the date)
               def =  dateHelper.splitDate(opts.startDate);
           }
           
           //give priority to the textbox which contains the date
           var t = jqsel.val();
            
           if(t == "" || t.length > 18 || t.length < 8){
               //not a date ignore
           }
           else{
               def = dateHelper.splitDate(t);
           } 
           //create the picker 
           var tbl = "<table class='picker-table'>"
           +"<tr class='picker-table-header'><td>DD</td><td>MM</td><td>YYYY</td><td>HH</td><td>MM</td></tr>"
           +"<tr class='picker-table-content'>"
           +"<td>"+this.privateHelper.renderDays(def[2])+"</td>"
           +"<td>"+this.privateHelper.renderMonths(def[1])+"</td>"
           +"<td>"+this.privateHelper.renderYears(def[0])+"</td>"
           +"<td>"+this.privateHelper.renderHours(def[3])+"</td>"
           +"<td>"+this.privateHelper.renderMinutes(def[4])+"</td>"
           +"</tr>"
           +"<tr class='picker-table-buttons'><td colspan='5'><a href='javascript:;' onclick='dateHelper.chooseDate(\""+sel+"\");' id='"+eachId+"-button'>Choose</a> | <a href='javascript:;' onclick='dateHelper.closePicker(\""+sel+"\");' id='"+eachId+"-picker'>Cancel</a></td></tr>"
           +"</table>";
           
           return tbl;
        },
        
        showPicker: function(){
            //show / hide
            var tbl = this.renderPicker();
            var str = "<div id='" + eachId + "-picker' style='display:none' class='picker-container'>" 
            + "<div class='picker-header'>Please choose a date</div>"
            + tbl + "</div>";
            jqsel.parent().append(str);
            $('#'+eachId+'-picker').fadeIn(600);
        },
        
        bindPicker: function(){
            var a = this;
            jqsel.bind('focus',function(){
                if ($("#"+eachId+"-picker").length == 0){
                    $('.picker-container').remove();
                    a.showPicker();
                }
                
            });
            
        },
        
        privateHelper:{
            
                renderDays: function (def){
                    def = typeof(def) == 'undefined' ? 0 : def;
                    var a = "<select name='"+eachId+"-2' id='"+eachId+"-2' size='1' class='picker-select-class'>";
                    for(var i=1;i<32;i++){
                        var b = i<10?"0"+i:i;
                        if(i==def){a += "<option value='"+ b +"' selected='selected'>"+ b +"</option>";}
                        else{a += "<option value='"+ b +"'>"+ b +"</option>";}
                    }
                    a+="</select>";
                    return a;
                },
                
                renderMonths: function (def){
                    def = typeof(def) == 'undefined' ? 0 : def;
                    var a = "<select name='"+eachId+"-1' id='"+eachId+"-1' size='1' class='picker-select-class'>";
                    for(var i=1;i<13;i++){
                        var b = i<10?"0"+i:i;
                        if(i==def){a += "<option value='"+ b +"' selected='selected'>"+ b +"</option>";}
                        else{a += "<option value='"+ b +"'>"+ b +"</option>";}
                    }
                    a+="</select>";
                    return a;
                },
                
                renderMonthsAsString: function (def){
                    return;
                },
                
                renderYears: function (def){
                    def = typeof(def) == 'undefined' ? 0 : def;
                    var a = "<select name='"+eachId+"-0' id='"+eachId+"-0' size='1' class='picker-select-class'>";
                    for(var i=parseFloat(dt_min[0]);i<=parseFloat(dt_max[0]);i++){
                        if(i==def){a += "<option value='"+ i +"' selected='selected'>"+ i +"</option>";}
                        else{a += "<option value='"+ i +"'>"+ i +"</option>";}
                    }
                    a+="</select>";
                    return a;    
                },
                
                renderHours: function (def){
                    def = typeof(def) == 'undefined' ? 0 : def;
                    var a = "<select name='"+eachId+"-3' id='"+eachId+"-3' size='1' class='picker-select-class'>";
                    for(var i=0;i<24;i++){
                        var b = i<10?"0"+i:i;
                        if(i==def){a += "<option value='"+ b +"' selected='selected'>"+ b +"</option>";}
                        else{a += "<option value='"+ b +"'>"+ b +"</option>";}
                    }
                    a+="</select>";
                    return a;
                },
                
                renderMinutes: function (def){
                    def = typeof(def) == 'undefined' ? 0 : def;
                    var a = "<select name='"+eachId+"-4' id='"+eachId+"-4' size='1' class='picker-select-class'>";
                    for(var i=0;i<60;i++){
                        var b = i<10?"0"+i:i;
                        if(i==def){a += "<option value='"+ b +"' selected='selected'>"+ b +"</option>";}
                        else{a += "<option value='"+ b +"'>"+ b +"</option>";}
                    }
                    a+="</select>";
                    return a;
                }                
                
            }
            
        }
    
    };
